Swing in Java
Swing in Java
Component
Container
JApplet JFrame
Classes in Brief
• Component : is an abstract class that encapsulates
all the attributes of a visual component.
• Container: It has other methods that allow other
components nested within it.
• Panel : is an window which does not have title
bar,menu bar or border.
• Window: It creates a top level window which sits
directly on the desktop. You won’t create object of
Window directly,but you can use subclass of
Window; that is Frame or JFrame
Example
Window based Application Program
Steps for window based application
program using Swing
1. javax.swing package is imported.
2. One container (JFrame / JApplet) is selected.
Jframe is for stand alone(desktop) and JApplet is
for internet application.[Java Server Faces]
3. Component objects are created and are added
into the container.[into JFrame object)
4. Event handling codes are written for the added
components as per the requirement
Window program using JFrame
Jlabel(String)
String getText()
void setText(String)
Methods of JTextField class
JTextField is an active component.(does respond to user
input)
JTextField( )
JTextField(int cols)
JTextField(String)
String getText()
void setText(String)
JButton( String)
}
Defining my class
import javax.swing;
class MyWindow{
JFrame j;
JLabel l;
}
Defining my class
import javax.swing;
class MyWindow{
JFrame j;
JLabel l;
// constructor
MyWindow(){
j=new Jframe(“My Window Program”);
j.setSize(100,200);
j. SetDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);
l=new JLabel(“Welcome”);
j.add(l);
j.setVisible(true);
}
}
Defining my class
import javax.swing;
class MyWindow{
JFrame j;
JLabel l;
MyWindow(){
j=new Jframe(“My Window Program”);
j.setSize(100,200);
j. SetDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);
l=new JLabel(“Welcome”);
j.add(l);
j.setVisible(true);
}
}
Defining my class
import javax.swing;
class MyWindow{
JFrame j;
JLabel l;
MyWindow(){
j=new Jframe(“My Window Program”);
j.setSize(100,200);
j. SetDefaultCloseOperation(Jframe.EXIT_ON_CLOSE);
l=new JLabel(“Welcome”);
j.add(l);
j.setVisible(true);
}
public static void main(String s[]){
new MySwing2();
}
public void actionPerformed(ActionEvent e){
if ((b.getActionCommand()).equals("click")){
l.setText("bye");
}
}
}