You are on page 1of 125

Java AWT

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based


applications in java.

Java AWT components are platform-dependent i.e. components are displayed according to
the view of operating system. AWT is heavyweight i.e. its components are using the
resources of OS.

The java.awt package provides classes for AWT api such as TextField, Label, TextArea,


RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below.
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such
as Frame, Dialog and Panel.

Window
The window is the container that have no borders and menu bars. You must use frame,
dialog or another window for creating a window.

Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.

Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
Java AWT Example
To create simple awt example, you need a frame. There are two ways to create a frame in
AWT.

o By extending Frame class (inheritance)


o By creating the object of Frame class (association)

AWT Example by Inheritance


Let's see a simple example of AWT where we are inheriting Frame class. Here, we are
showing Button component on the Frame.

1. import java.awt.*;  
2. class First extends Frame{  
3. First(){  
4. Button b=new Button("click me");  
5. b.setBounds(30,100,80,30);// setting button position  
6. add(b);//adding button into frame  
7. setSize(300,300);//frame size 300 width and 300 height  
8. setLayout(null);//no layout manager  
9. setVisible(true);//now frame will be visible, by default not visible  
10. }  
11. public static void main(String args[]){  
12. First f=new First();  
13. }}  

The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above
example that sets the position of the awt button.

AWT Example by Association


Let's see a simple example of AWT where we are creating instance of Frame class. Here, we
are showing Button component on the Frame.

1. import java.awt.*;  
2. class First2{  
3. First2(){  
4. Frame f=new Frame();  
5. Button b=new Button("click me");  
6. b.setBounds(30,50,80,30);  
7. f.add(b);  
8. f.setSize(300,300);  
9. f.setLayout(null);  
10. f.setVisible(true);  
11. }  
12. public static void main(String args[]){  
13. First2 f=new First2();  
14. }}  

Event and Listener (Java Event Handling)


Changing the state of an object is known as an event. For example, click on button, dragging mouse etc
interfaces for event handling.

Java Event classes and Listener interfaces


Steps to perform Event Handling
Following steps are required to perform event handling:

1. Register the component with the Listener

Registration Methods
For registering the component with the Listener, many classes provide the registration
methods. For example:

o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Java Event Handling Code


We can put the event handling code into one of the following places:

1. Within class
2. Other class
3. Anonymous class

Java event handling by implementing ActionListener


1. import java.awt.*;  
2. import java.awt.event.*;  
3. class AEvent extends Frame implements ActionListener{  
4. TextField tf;  
5. AEvent(){  
6.   
7. //create components  
8. tf=new TextField();  
9. tf.setBounds(60,50,170,20);  
10. Button b=new Button("click me");  
11. b.setBounds(100,120,80,30);  
12.   
13. //register listener  
14. b.addActionListener(this);//passing current instance  
15.   
16. //add components and set size, layout and visibility  
17. add(b);add(tf);  
18. setSize(300,300);  
19. setLayout(null);  
20. setVisible(true);  
21. }  
22. public void actionPerformed(ActionEvent e){  
23. tf.setText("Welcome");  
24. }  
25. public static void main(String args[]){  
26. new AEvent();  
27. }  
28. }  

public void setBounds(int xaxis, int yaxis, int width, int height); have been used in
the above example that sets the position of the component it may be button, textfield etc.
2) Java event handling by outer class
1. import java.awt.*;  
2. import java.awt.event.*;  
3. class AEvent2 extends Frame{  
4. TextField tf;  
5. AEvent2(){  
6. //create components  
7. tf=new TextField();  
8. tf.setBounds(60,50,170,20);  
9. Button b=new Button("click me");  
10. b.setBounds(100,120,80,30);  
11. //register listener  
12. Outer o=new Outer(this);  
13. b.addActionListener(o);//passing outer class instance  
14. //add components and set size, layout and visibility  
15. add(b);add(tf);  
16. setSize(300,300);  
17. setLayout(null);  
18. setVisible(true);  
19. }  
20. public static void main(String args[]){  
21. new AEvent2();  
22. }  
23. }  

1. import java.awt.event.*;  
2. class Outer implements ActionListener{  
3. AEvent2 obj;  
4. Outer(AEvent2 obj){  
5. this.obj=obj;  
6. }  
7. public void actionPerformed(ActionEvent e){  
8. obj.tf.setText("welcome");  
9. }  
10. }  

3) Java event handling by anonymous class


1. import java.awt.*;  
2. import java.awt.event.*;  
3. class AEvent3 extends Frame{  
4. TextField tf;  
5. AEvent3(){  
6. tf=new TextField();  
7. tf.setBounds(60,50,170,20);  
8. Button b=new Button("click me");  
9. b.setBounds(50,120,80,30);  
10.   
11. b.addActionListener(new ActionListener(){  
12. public void actionPerformed(){  
13. tf.setText("hello");  
14. }  
15. });  
16. add(b);add(tf);  
17. setSize(300,300);  
18. setLayout(null);  
19. setVisible(true);  
20. }  
21. public static void main(String args[]){  
22. new AEvent3();  
23. }  
24. }  

Java AWT Button


The button class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed.

AWT Button Class declaration


1. public class Button extends Component implements Accessible  

Java AWT Button Example


1. import java.awt.*;  
2. public class ButtonExample {  
3. public static void main(String[] args) {  
4.     Frame f=new Frame("Button Example");  
5.     Button b=new Button("Click Here");  
6.     b.setBounds(50,100,80,30);  
7.     f.add(b);  
8.     f.setSize(400,400);  
9.     f.setLayout(null);  
10.     f.setVisible(true);   
11. }  
12. }  

Output:
Java AWT Button Example with ActionListener
1. import java.awt.*;  
2. import java.awt.event.*;  
3. public class ButtonExample {  
4. public static void main(String[] args) {  
5.     Frame f=new Frame("Button Example");  
6.     final TextField tf=new TextField();  
7.     tf.setBounds(50,50, 150,20);  
8.     Button b=new Button("Click Here");  
9.     b.setBounds(50,100,60,30);  
10.     b.addActionListener(new ActionListener(){  
11.     public void actionPerformed(ActionEvent e){  
12.             tf.setText("Welcome to Javatpoint.");  
13.         }  
14.     });  
15.     f.add(b);f.add(tf);  
16.     f.setSize(400,400);  
17.     f.setLayout(null);  
18.     f.setVisible(true);   
19. }  
20. }  

Output:
Java AWT Label
The object of Label class is a component for placing text in a container. It is used to display
a single line of read only text. The text can be changed by an application but a user cannot
edit it directly.

AWT Label Class Declaration


1. public class Label extends Component implements Accessible  

Java Label Example


1. import java.awt.*;  
2. class LabelExample{  
3. public static void main(String args[]){  
4.     Frame f= new Frame("Label Example");  
5.     Label l1,l2;  
6.     l1=new Label("First Label.");  
7.     l1.setBounds(50,100, 100,30);  
8.     l2=new Label("Second Label.");  
9.     l2.setBounds(50,150, 100,30);  
10.     f.add(l1); f.add(l2);  
11.     f.setSize(400,400);  
12.     f.setLayout(null);  
13.     f.setVisible(true);  
14. }  
15. }  

Output:

Java AWT Label Example with ActionListener


1. import java.awt.*;  
2. import java.awt.event.*;  
3. public class LabelExample extends Frame implements ActionListener{  
4.     TextField tf; Label l; Button b;  
5.     LabelExample(){  
6.         tf=new TextField();  
7.         tf.setBounds(50,50, 150,20);  
8.         l=new Label();  
9.         l.setBounds(50,100, 250,20);      
10.         b=new Button("Find IP");  
11.         b.setBounds(50,150,60,30);  
12.         b.addActionListener(this);    
13.         add(b);add(tf);add(l);    
14.         setSize(400,400);  
15.         setLayout(null);  
16.         setVisible(true);  
17.     }  
18.     public void actionPerformed(ActionEvent e) {  
19.         try{  
20.         String host=tf.getText();  
21.         String ip=java.net.InetAddress.getByName(host).getHostAddress();  
22.         l.setText("IP of "+host+" is: "+ip);  
23.         }catch(Exception ex){System.out.println(ex);}  
24.     }  
25.     public static void main(String[] args) {  
26.         new LabelExample();  
27.     }  
28. }  

Output:

Java AWT TextField


The object of a TextField class is a text component that allows the editing of a single line
text. It inherits TextComponent class.

AWT TextField Class Declaration


1. public class TextField extends TextComponent  
Java AWT TextField Example
1. import java.awt.*;  
2. class TextFieldExample{  
3. public static void main(String args[]){  
4.     Frame f= new Frame("TextField Example");  
5.     TextField t1,t2;  
6.     t1=new TextField("Welcome to Javatpoint.");  
7.     t1.setBounds(50,100, 200,30);  
8.     t2=new TextField("AWT Tutorial");  
9.     t2.setBounds(50,150, 200,30);  
10.     f.add(t1); f.add(t2);  
11.     f.setSize(400,400);  
12.     f.setLayout(null);  
13.     f.setVisible(true);  
14. }  
15. }  

Output:

Java AWT TextField Example with ActionListener


1. import java.awt.*;  
2. import java.awt.event.*;  
3. public class TextFieldExample extends Frame implements ActionListener{  
4.     TextField tf1,tf2,tf3;  
5.     Button b1,b2;  
6.     TextFieldExample(){  
7.         tf1=new TextField();  
8.         tf1.setBounds(50,50,150,20);  
9.         tf2=new TextField();  
10.         tf2.setBounds(50,100,150,20);  
11.         tf3=new TextField();  
12.         tf3.setBounds(50,150,150,20);  
13.         tf3.setEditable(false);   
14.         b1=new Button("+");  
15.         b1.setBounds(50,200,50,50);  
16.         b2=new Button("-");  
17.         b2.setBounds(120,200,50,50);  
18.         b1.addActionListener(this);  
19.         b2.addActionListener(this);  
20.         add(tf1);add(tf2);add(tf3);add(b1);add(b2);  
21.         setSize(300,300);  
22.         setLayout(null);  
23.         setVisible(true);  
24.     }         
25.     public void actionPerformed(ActionEvent e) {  
26.         String s1=tf1.getText();  
27.         String s2=tf2.getText();  
28.         int a=Integer.parseInt(s1);  
29.         int b=Integer.parseInt(s2);  
30.         int c=0;  
31.         if(e.getSource()==b1){  
32.             c=a+b;  
33.         }else if(e.getSource()==b2){  
34.             c=a-b;  
35.         }  
36.         String result=String.valueOf(c);  
37.         tf3.setText(result);  
38.     }  
39. public static void main(String[] args) {  
40.     new TextFieldExample();  
41. }  
42. }  

Output:

Java AWT TextArea


The object of a TextArea class is a multi line region that displays text. It allows the editing
of multiple line text. It inherits TextComponent class.

AWT TextArea Class Declaration


1. public class TextArea extends TextComponent  

Java AWT TextArea Example


1. import java.awt.*;  
2. public class TextAreaExample  
3. {  
4.      TextAreaExample(){  
5.         Frame f= new Frame();  
6.             TextArea area=new TextArea("Welcome to javatpoint");  
7.         area.setBounds(10,30, 300,300);  
8.         f.add(area);  
9.         f.setSize(400,400);  
10.         f.setLayout(null);  
11.         f.setVisible(true);  
12.      }  
13. public static void main(String args[])  
14. {  
15.    new TextAreaExample();  
16. }  
17. }  

Output:

Java AWT TextArea Example with ActionListener


1. import java.awt.*;  
2. import java.awt.event.*;  
3. public class TextAreaExample extends Frame implements ActionListener{  
4. Label l1,l2;  
5. TextArea area;  
6. Button b;  
7. TextAreaExample(){  
8.     l1=new Label();  
9.     l1.setBounds(50,50,100,30);  
10.     l2=new Label();  
11.     l2.setBounds(160,50,100,30);  
12.     area=new TextArea();  
13.     area.setBounds(20,100,300,300);  
14.     b=new Button("Count Words");  
15.     b.setBounds(100,400,100,30);  
16.     b.addActionListener(this);  
17.     add(l1);add(l2);add(area);add(b);  
18.     setSize(400,450);  
19.     setLayout(null);  
20.     setVisible(true);  
21. }  
22. public void actionPerformed(ActionEvent e){  
23.     String text=area.getText();  
24.     String words[]=text.split("\\s");  
25.     l1.setText("Words: "+words.length);  
26.     l2.setText("Characters: "+text.length());  
27. }  
28. public static void main(String[] args) {  
29.     new TextAreaExample();  
30. }  
31. }  

Output:
Java AWT Checkbox
The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".

AWT Checkbox Class Declaration


1. public class Checkbox extends Component implements ItemSelectable, Accessible  

Java AWT Checkbox Example


1. import java.awt.*;  
2. public class CheckboxExample  
3. {  
4.      CheckboxExample(){  
5.        Frame f= new Frame("Checkbox Example");  
6.         Checkbox checkbox1 = new Checkbox("C++");  
7.         checkbox1.setBounds(100,100, 50,50);  
8.         Checkbox checkbox2 = new Checkbox("Java", true);  
9.         checkbox2.setBounds(100,150, 50,50);  
10.         f.add(checkbox1);  
11.         f.add(checkbox2);  
12.         f.setSize(400,400);  
13.         f.setLayout(null);  
14.         f.setVisible(true);  
15.      }  
16. public static void main(String args[])  
17. {  
18.     new CheckboxExample();  
19. }  
20. }  

Output:
Java AWT CheckboxGroup
The object of CheckboxGroup class is used to group together a set of Checkbox. At a time
only one check box button is allowed to be in "on" state and remaining check box button in
"off" state. It inherits the object class.

Note: CheckboxGroup enables you to create radio buttons in AWT. There is no special
control for creating radio buttons in AWT.

AWT CheckboxGroup Class Declaration


1. public class CheckboxGroup extends Object implements Serializable  

Java AWT CheckboxGroup Example


1. import java.awt.*;    
2. public class CheckboxGroupExample    
3. {    
4.        CheckboxGroupExample(){    
5.        Frame f= new Frame("CheckboxGroup Example");    
6.         CheckboxGroup cbg = new CheckboxGroup();  
7.         Checkbox checkBox1 = new Checkbox("C++", cbg, false);    
8.         checkBox1.setBounds(100,100, 50,50);    
9.         Checkbox checkBox2 = new Checkbox("Java", cbg, true);    
10.         checkBox2.setBounds(100,150, 50,50);    
11.         f.add(checkBox1);    
12.         f.add(checkBox2);    
13.         f.setSize(400,400);    
14.         f.setLayout(null);    
15.         f.setVisible(true);    
16.      }    
17. public static void main(String args[])    
18. {    
19.     new CheckboxGroupExample();    
20. }    
21. }  

Output:
Java AWT CheckboxGroup Example with ItemListener
1. import java.awt.*;    
2. import java.awt.event.*;  
3. public class CheckboxGroupExample    
4. {    
5.      CheckboxGroupExample(){    
6.        Frame f= new Frame("CheckboxGroup Example");    
7.        final Label label = new Label();          
8.        label.setAlignment(Label.CENTER);  
9.        label.setSize(400,100);  
10.         CheckboxGroup cbg = new CheckboxGroup();  
11.         Checkbox checkBox1 = new Checkbox("C++", cbg, false);    
12.         checkBox1.setBounds(100,100, 50,50);    
13.         Checkbox checkBox2 = new Checkbox("Java", cbg, false);    
14.         checkBox2.setBounds(100,150, 50,50);    
15.         f.add(checkBox1); f.add(checkBox2); f.add(label);    
16.         f.setSize(400,400);    
17.         f.setLayout(null);    
18.         f.setVisible(true);    
19.         checkBox1.addItemListener(new ItemListener() {  
20.             public void itemStateChanged(ItemEvent e) {               
21.                label.setText("C++ checkbox: Checked");  
22.             }  
23.          });  
24.         checkBox2.addItemListener(new ItemListener() {  
25.             public void itemStateChanged(ItemEvent e) {               
26.                label.setText("Java checkbox: Checked");  
27.             }  
28.          });  
29.      }    
30. public static void main(String args[])    
31. {    
32.     new CheckboxGroupExample();    
33. }    
34. }  

Output:

Java AWT Choice


The object of Choice class is used to show popup menu of choices. Choice selected by user
is shown on the top of a menu. It inherits Component class.

AWT Choice Class Declaration


1. public class Choice extends Component implements ItemSelectable, Accessible  
Java AWT Choice Example
1. import java.awt.*;  
2. public class ChoiceExample  
3. {  
4.         ChoiceExample(){  
5.         Frame f= new Frame();  
6.         Choice c=new Choice();  
7.         c.setBounds(100,100, 75,75);  
8.         c.add("Item 1");  
9.         c.add("Item 2");  
10.         c.add("Item 3");  
11.         c.add("Item 4");  
12.         c.add("Item 5");  
13.         f.add(c);  
14.         f.setSize(400,400);  
15.         f.setLayout(null);  
16.         f.setVisible(true);  
17.      }  
18. public static void main(String args[])  
19. {  
20.    new ChoiceExample();  
21. }  
22. }  

Output:
Java AWT Choice Example with ActionListener
1. import java.awt.*;  
2. import java.awt.event.*;  
3. public class ChoiceExample  
4. {  
5.         ChoiceExample(){  
6.         Frame f= new Frame();  
7.         final Label label = new Label();          
8.         label.setAlignment(Label.CENTER);  
9.         label.setSize(400,100);  
10.         Button b=new Button("Show");  
11.         b.setBounds(200,100,50,20);  
12.         final Choice c=new Choice();  
13.         c.setBounds(100,100, 75,75);  
14.         c.add("C");  
15.         c.add("C++");  
16.         c.add("Java");  
17.         c.add("PHP");  
18.         c.add("Android");  
19.         f.add(c);f.add(label); f.add(b);  
20.         f.setSize(400,400);  
21.         f.setLayout(null);  
22.         f.setVisible(true);  
23.         b.addActionListener(new ActionListener() {  
24.             public void actionPerformed(ActionEvent e) {       
25.          String data = "Programming language Selected: "+ c.getItem(c.getSelectedIndex());  
26.          label.setText(data);  
27.         }  
28.         });           
29.         }  
30. public static void main(String args[])  
31. {  
32.    new ChoiceExample();  
33. }  
34. }  

Output:
Java AWT List
The object of List class represents a list of text items. By the help of list, user can choose
either one item or multiple items. It inherits Component class.

AWT List class Declaration


1. public class List extends Component implements ItemSelectable, Accessible  

Java AWT List Example


1. import java.awt.*;  
2. public class ListExample  
3. {  
4.      ListExample(){  
5.         Frame f= new Frame();  
6.         List l1=new List(5);  
7.         l1.setBounds(100,100, 75,75);  
8.         l1.add("Item 1");  
9.         l1.add("Item 2");  
10.         l1.add("Item 3");  
11.         l1.add("Item 4");  
12.         l1.add("Item 5");  
13.         f.add(l1);  
14.         f.setSize(400,400);  
15.         f.setLayout(null);  
16.         f.setVisible(true);  
17.      }  
18. public static void main(String args[])  
19. {  
20.    new ListExample();  
21. }  
22. }  

Output:

Java AWT List Example with ActionListener


1. import java.awt.*;  
2. import java.awt.event.*;  
3. public class ListExample  
4. {  
5.      ListExample(){  
6.         Frame f= new Frame();  
7.         final Label label = new Label();          
8.         label.setAlignment(Label.CENTER);  
9.         label.setSize(500,100);  
10.         Button b=new Button("Show");  
11.         b.setBounds(200,150,80,30);  
12.         final List l1=new List(4, false);  
13.         l1.setBounds(100,100, 70,70);  
14.         l1.add("C");  
15.         l1.add("C++");  
16.         l1.add("Java");  
17.         l1.add("PHP");  
18.         final List l2=new List(4, true);  
19.         l2.setBounds(100,200, 70,70);  
20.         l2.add("Turbo C++");  
21.         l2.add("Spring");  
22.         l2.add("Hibernate");  
23.         l2.add("CodeIgniter");  
24.         f.add(l1); f.add(l2); f.add(label); f.add(b);  
25.         f.setSize(450,450);  
26.         f.setLayout(null);  
27.         f.setVisible(true);  
28.         b.addActionListener(new ActionListener() {  
29.          public void actionPerformed(ActionEvent e) {       
30.           String data = "Programming language Selected: "+l1.getItem(l1.getSelectedIndex())
;  
31.           data += ", Framework Selected:";  
32.           for(String frame:l2.getSelectedItems()){  
33.                    data += frame + " ";  
34.           }  
35.           label.setText(data);  
36.           }  
37.          });          
38. }  
39. public static void main(String args[])  
40. {  
41.    new ListExample();  
42. }  
43. }  

Output:
Java AWT Canvas
The Canvas control represents a blank rectangular area where the application can draw or
trap input events from the user. It inherits the Component class.

AWT Canvas class Declaration


1. public class Canvas extends Component implements Accessible  

Java AWT Canvas Example


1. import java.awt.*;  
2. public class CanvasExample  
3. {  
4.   public CanvasExample()  
5.   {  
6.     Frame f= new Frame("Canvas Example");  
7.     f.add(new MyCanvas());  
8.     f.setLayout(null);  
9.     f.setSize(400, 400);  
10.     f.setVisible(true);  
11.   }  
12.   public static void main(String args[])  
13.   {  
14.     new CanvasExample();  
15.   }  
16. }  
17. class MyCanvas extends Canvas  
18. {  
19.         public MyCanvas() {  
20.         setBackground (Color.GRAY);  
21.         setSize(300, 200);  
22.      }  
23.   public void paint(Graphics g)  
24.   {  
25.     g.setColor(Color.red);  
26.     g.fillOval(75, 75, 150, 75);  
27.   }  
28. }    

Output:
Java AWT Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is
a GUI component allows us to see invisible number of rows and columns.

AWT Scrollbar class declaration


1. public class Scrollbar extends Component implements Adjustable, Accessible  

Java AWT Scrollbar Example


1. import java.awt.*;  
2. class ScrollbarExample{  
3. ScrollbarExample(){  
4.             Frame f= new Frame("Scrollbar Example");  
5.             Scrollbar s=new Scrollbar();  
6.             s.setBounds(100,100, 50,100);  
7.             f.add(s);  
8.             f.setSize(400,400);  
9.             f.setLayout(null);  
10.             f.setVisible(true);  
11. }  
12. public static void main(String args[]){  
13.        new ScrollbarExample();  
14. }  
15. }  

Output:
Java AWT Scrollbar Example with AdjustmentListener
1. import java.awt.*;  
2. import java.awt.event.*;  
3. class ScrollbarExample{  
4.      ScrollbarExample(){  
5.             Frame f= new Frame("Scrollbar Example");  
6.             final Label label = new Label();          
7.             label.setAlignment(Label.CENTER);  
8.             label.setSize(400,100);  
9.             final Scrollbar s=new Scrollbar();  
10.             s.setBounds(100,100, 50,100);  
11.             f.add(s);f.add(label);   
12.             f.setSize(400,400);  
13.             f.setLayout(null);  
14.             f.setVisible(true);  
15.             s.addAdjustmentListener(new AdjustmentListener() {  
16.                 public void adjustmentValueChanged(AdjustmentEvent e) {  
17.                    label.setText("Vertical Scrollbar value is:"+ s.getValue());  
18.                 }  
19.             });  
20.          }  
21. public static void main(String args[]){  
22. new ScrollbarExample();  
23. }  
24. }  

Output:

Java AWT MenuItem and Menu


The object of MenuItem class adds a simple labeled menu item on menu. The items used in
a menu must belong to the MenuItem or any of its subclass.

The object of Menu class is a pull down menu component which is displayed on the menu
bar. It inherits the MenuItem class.

AWT MenuItem class declaration


1. public class MenuItem extends MenuComponent implements Accessible  
AWT Menu class declaration
1. public class Menu extends MenuItem implements MenuContainer, Accessible  

Java AWT MenuItem and Menu Example


1. import java.awt.*;  
2. class MenuExample  
3. {  
4.      MenuExample(){  
5.          Frame f= new Frame("Menu and MenuItem Example");  
6.          MenuBar mb=new MenuBar();  
7.          Menu menu=new Menu("Menu");  
8.          Menu submenu=new Menu("Sub Menu");  
9.          MenuItem i1=new MenuItem("Item 1");  
10.          MenuItem i2=new MenuItem("Item 2");  
11.          MenuItem i3=new MenuItem("Item 3");  
12.          MenuItem i4=new MenuItem("Item 4");  
13.          MenuItem i5=new MenuItem("Item 5");  
14.          menu.add(i1);  
15.          menu.add(i2);  
16.          menu.add(i3);  
17.          submenu.add(i4);  
18.          submenu.add(i5);  
19.          menu.add(submenu);  
20.          mb.add(menu);  
21.          f.setMenuBar(mb);  
22.          f.setSize(400,400);  
23.          f.setLayout(null);  
24.          f.setVisible(true);  
25. }  
26. public static void main(String args[])  
27. {  
28. new MenuExample();  
29. }  
30. }  

Output:
Java AWT PopupMenu
PopupMenu can be dynamically popped up at specific position within a component. It
inherits the Menu class.

AWT PopupMenu class declaration


1. public class PopupMenu extends Menu implements MenuContainer, Accessible  

Java AWT PopupMenu Example


1. import java.awt.*;  
2. import java.awt.event.*;  
3. class PopupMenuExample  
4. {  
5.      PopupMenuExample(){  
6.          final Frame f= new Frame("PopupMenu Example");  
7.          final PopupMenu popupmenu = new PopupMenu("Edit");   
8.          MenuItem cut = new MenuItem("Cut");  
9.          cut.setActionCommand("Cut");  
10.          MenuItem copy = new MenuItem("Copy");  
11.          copy.setActionCommand("Copy");  
12.          MenuItem paste = new MenuItem("Paste");  
13.          paste.setActionCommand("Paste");      
14.          popupmenu.add(cut);  
15.          popupmenu.add(copy);  
16.          popupmenu.add(paste);        
17.          f.addMouseListener(new MouseAdapter() {  
18.             public void mouseClicked(MouseEvent e) {              
19.                 popupmenu.show(f , e.getX(), e.getY());  
20.             }                 
21.          });  
22.          f.add(popupmenu);   
23.          f.setSize(400,400);  
24.          f.setLayout(null);  
25.          f.setVisible(true);  
26.      }  
27. public static void main(String args[])  
28. {  
29.         new PopupMenuExample();  
30. }  
31. }  

Output:
 

Java AWT Panel


The Panel is a simplest container class. It provides space in which an application can attach
any other component. It inherits the Container class.

It doesn't have title bar.

AWT Panel class declaration


1. public class Panel extends Container implements Accessible  

Java AWT Panel Example


1. import java.awt.*;  
2. public class PanelExample {  
3.      PanelExample()  
4.         {  
5.         Frame f= new Frame("Panel Example");    
6.         Panel panel=new Panel();  
7.         panel.setBounds(40,80,200,200);    
8.         panel.setBackground(Color.gray);  
9.         Button b1=new Button("Button 1");     
10.         b1.setBounds(50,100,80,30);    
11.         b1.setBackground(Color.yellow);   
12.         Button b2=new Button("Button 2");   
13.         b2.setBounds(100,100,80,30);    
14.         b2.setBackground(Color.green);   
15.         panel.add(b1); panel.add(b2);  
16.         f.add(panel);  
17.         f.setSize(400,400);    
18.         f.setLayout(null);    
19.         f.setVisible(true);    
20.         }  
21.         public static void main(String args[])  
22.         {  
23.         new PanelExample();  
24.         }  
25. }  

Output:
Java AWT Dialog
The Dialog control represents a top level window with a border and a title used to take some
form of input from the user. It inherits the Window class.

Unlike Frame, it doesn't have maximize and minimize buttons.

Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons
but Dialog doesn't have.

AWT Dialog class declaration


1. public class Dialog extends Window  
Java AWT Dialog Example
1. import java.awt.*;  
2. import java.awt.event.*;  
3. public class DialogExample {  
4.     private static Dialog d;  
5.     DialogExample() {  
6.         Frame f= new Frame();  
7.         d = new Dialog(f , "Dialog Example", true);  
8.         d.setLayout( new FlowLayout() );  
9.         Button b = new Button ("OK");  
10.         b.addActionListener ( new ActionListener()  
11.         {  
12.             public void actionPerformed( ActionEvent e )  
13.             {  
14.                 DialogExample.d.setVisible(false);  
15.             }  
16.         });  
17.         d.add( new Label ("Click button to continue."));  
18.         d.add(b);   
19.         d.setSize(300,300);    
20.         d.setVisible(true);  
21.     }  
22.     public static void main(String args[])  
23.     {  
24.         new DialogExample();  
25.     }  
26. }  

Output:
Java AWT Toolkit
Toolkit class is the abstract superclass of every implementation in the Abstract Window
Toolkit. Subclasses of Toolkit are used to bind various components. It inherits Object class.

AWT Toolkit class declaration


1. public abstract class Toolkit extends Object  

Java AWT Toolkit Example


1. import java.awt.*;  
2. public class ToolkitExample {  
3.   public static void main(String[] args) {  
4.       Toolkit t = Toolkit.getDefaultToolkit();  
5.       System.out.println("Screen resolution = " + t.getScreenResolution());  
6.       Dimension d = t.getScreenSize();  
7.       System.out.println("Screen width = " + d.width);  
8.       System.out.println("Screen height = " + d.height);  
9.   }  
10. }  

Output:
Screen resolution = 96
Screen width = 1366
Screen height = 768

Java AWT Toolkit Example: beep()


1. import java.awt.event.*;  
2. public class ToolkitExample {  
3. public static void main(String[] args) {  
4.     Frame f=new Frame("ToolkitExample");  
5.     Button b=new Button("beep");  
6.     b.setBounds(50,100,60,30);  
7.     f.add(b);     
8.     f.setSize(300,300);  
9.     f.setLayout(null);  
10.     f.setVisible(true);  
11.     b.addActionListener(new ActionListener(){  
12.         public void actionPerformed(ActionEvent e){  
13.             Toolkit.getDefaultToolkit().beep();  
14.         }  
15.     });       
16. }  
17. }  

Output:
Java AWT Toolkit Example: Change TitleBar Icon
1. import java.awt.*;   
2. class ToolkitExample {   
3. ToolkitExample(){   
4. Frame f=new Frame();   
5. Image icon = Toolkit.getDefaultToolkit().getImage("D:\\icon.png");  
6. f.setIconImage(icon);  
7. f.setLayout(null);   
8. f.setSize(400,400);   
9. f.setVisible(true);   
10. }   
11. public static void main(String args[]){   
12. new ToolkitExample();   
13. }   
14. }  

Output:
Java ActionListener Interface
The Java ActionListener is notified whenever you click on the button or menu item. It is
notified against ActionEvent. The ActionListener interface is found in
java.awt.event package. It has only one method: actionPerformed().

actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on the
registered component.

1. public abstract void actionPerformed(ActionEvent e);  

How to write ActionListener


The common approach is to implement the ActionListener. If you implement the
ActionListener class, you need to follow 3 steps:
) Implement the ActionListener interface in the class:

1. public class ActionListenerExample Implements ActionListener  

2) Register the component with the Listener:

1. component.addActionListener(instanceOfListenerclass);  

3) Override the actionPerformed() method:

1. public void actionPerformed(ActionEvent e){  
2.            //Write the code here  
3. }  

Java ActionListener Example: On Button click


1. import java.awt.*;  
2. import java.awt.event.*;  
3. //1st step  
4. public class ActionListenerExample implements ActionListener{  
5. public static void main(String[] args) {  
6.     Frame f=new Frame("ActionListener Example");  
7.     final TextField tf=new TextField();  
8.     tf.setBounds(50,50, 150,20);  
9.     Button b=new Button("Click Here");  
10.     b.setBounds(50,100,60,30);  
11.     //2nd step  
12.     b.addActionListener(this);  
13.     f.add(b);f.add(tf);  
14.     f.setSize(400,400);  
15.     f.setLayout(null);  
16.     f.setVisible(true);   
17. }  
18. //3rd step  
19. public void actionPerformed(ActionEvent e){  
20.             tf.setText("Welcome to Javatpoint.");  
21. }  
22. }  

Output:
Java ActionListener Example: Using Anonymous class
We can also use the anonymous class to implement the ActionListener. It is the shorthand
way, so you do not need to follow the 3 steps:

1. b.addActionListener(new ActionListener(){  
2. public void actionPerformed(ActionEvent e){  
3.            tf.setText("Welcome to Javatpoint.");  
4. }  
5. });  

Let us see the full code of ActionListener using anonymous class.

1. import java.awt.*;  
2. import java.awt.event.*;  
3. public class ActionListenerExample {  
4. public static void main(String[] args) {  
5.     Frame f=new Frame("ActionListener Example");  
6.     final TextField tf=new TextField();  
7.     tf.setBounds(50,50, 150,20);  
8.     Button b=new Button("Click Here");  
9.     b.setBounds(50,100,60,30);  
10.   
11.     b.addActionListener(new ActionListener(){  
12.     public void actionPerformed(ActionEvent e){  
13.             tf.setText("Welcome to Javatpoint.");  
14.     }  
15.     });  
16.     f.add(b);f.add(tf);  
17.     f.setSize(400,400);  
18.     f.setLayout(null);  
19.     f.setVisible(true);   
20. }  
21. }  

Output:

Java MouseListener Interface


The Java MouseListener is notified whenever you change the state of mouse. It is notified
against MouseEvent. The MouseListener interface is found in java.awt.event package. It has
five methods.

Methods of MouseListener interface


The signature of 5 methods found in MouseListener interface are given below:

1. public abstract void mouseClicked(MouseEvent e);  
2. public abstract void mouseEntered(MouseEvent e);  
3. public abstract void mouseExited(MouseEvent e);  
4. public abstract void mousePressed(MouseEvent e);  
5. public abstract void mouseReleased(MouseEvent e);  
Java MouseListener Example
1. import java.awt.*;  
2. import java.awt.event.*;  
3. public class MouseListenerExample extends Frame implements MouseListener{  
4.     Label l;  
5.     MouseListenerExample(){  
6.         addMouseListener(this);  
7.           
8.         l=new Label();  
9.         l.setBounds(20,50,100,20);  
10.         add(l);  
11.         setSize(300,300);  
12.         setLayout(null);  
13.         setVisible(true);  
14.     }  
15.     public void mouseClicked(MouseEvent e) {  
16.         l.setText("Mouse Clicked");  
17.     }  
18.     public void mouseEntered(MouseEvent e) {  
19.         l.setText("Mouse Entered");  
20.     }  
21.     public void mouseExited(MouseEvent e) {  
22.         l.setText("Mouse Exited");  
23.     }  
24.     public void mousePressed(MouseEvent e) {  
25.         l.setText("Mouse Pressed");  
26.     }  
27.     public void mouseReleased(MouseEvent e) {  
28.         l.setText("Mouse Released");  
29.     }  
30. public static void main(String[] args) {  
31.     new MouseListenerExample();  
32. }  
33. }  

Output:
Java MouseListener Example 2
1. import java.awt.*;  
2. import java.awt.event.*;  
3. public class MouseListenerExample2 extends Frame implements MouseListener{  
4.     MouseListenerExample2(){  
5.         addMouseListener(this);  
6.           
7.         setSize(300,300);  
8.         setLayout(null);  
9.         setVisible(true);  
10.     }  
11.     public void mouseClicked(MouseEvent e) {  
12.         Graphics g=getGraphics();  
13.         g.setColor(Color.BLUE);  
14.         g.fillOval(e.getX(),e.getY(),30,30);  
15.     }  
16.     public void mouseEntered(MouseEvent e) {}  
17.     public void mouseExited(MouseEvent e) {}  
18.     public void mousePressed(MouseEvent e) {}  
19.     public void mouseReleased(MouseEvent e) {}  
20.       
21. public static void main(String[] args) {  
22.     new MouseListenerExample2();  
23. }  
24. }  

Output:

Java MouseMotionListener Interface


The Java MouseMotionListener is notified whenever you move or drag mouse. It is notified
against MouseEvent. The MouseMotionListener interface is found in java.awt.event package.
It has two methods.

Methods of MouseMotionListener interface


The signature of 2 methods found in MouseMotionListener interface are given below:

1. public abstract void mouseDragged(MouseEvent e);  
2. public abstract void mouseMoved(MouseEvent e);  

Java MouseMotionListener Example


1. import java.awt.*;  
2. import java.awt.event.*;  
3. public class MouseMotionListenerExample extends Frame implements MouseMotionListe
ner{  
4.     MouseMotionListenerExample(){  
5.         addMouseMotionListener(this);  
6.           
7.         setSize(300,300);  
8.         setLayout(null);  
9.         setVisible(true);  
10.     }  
11. public void mouseDragged(MouseEvent e) {  
12.     Graphics g=getGraphics();  
13.     g.setColor(Color.BLUE);  
14.     g.fillOval(e.getX(),e.getY(),20,20);  
15. }  
16. public void mouseMoved(MouseEvent e) {}  
17.   
18. public static void main(String[] args) {  
19.     new MouseMotionListenerExample();  
20. }  
21. }  

Output:
Java MouseMotionListener Example 2
1. import java.awt.*;  
2. import java.awt.event.MouseEvent;  
3. import java.awt.event.MouseMotionListener;  
4. public class Paint extends Frame implements MouseMotionListener{  
5.     Label l;  
6.     Color c=Color.BLUE;  
7.     Paint(){  
8.     l=new Label();  
9.     l.setBounds(20,40,100,20);  
10.     add(l);  
11.       
12.     addMouseMotionListener(this);  
13.       
14.     setSize(400,400);  
15.     setLayout(null);  
16.     setVisible(true);  
17. }  
18. public void mouseDragged(MouseEvent e) {  
19.     l.setText("X="+e.getX()+", Y="+e.getY());  
20.     Graphics g=getGraphics();  
21.     g.setColor(Color.RED);  
22.     g.fillOval(e.getX(),e.getY(),20,20);  
23. }  
24. public void mouseMoved(MouseEvent e) {  
25.     l.setText("X="+e.getX()+", Y="+e.getY());  
26. }  
27. public static void main(String[] args) {  
28.     new Paint();  
29. }  
30. }  

Output:
Java ItemListener Interface
The Java ItemListener is notified whenever you click on the checkbox. It is notified against
ItemEvent. The ItemListener interface is found in java.awt.event package. It has only one
method: itemStateChanged().

itemStateChanged() method
The itemStateChanged() method is invoked automatically whenever you click or unclick on
the registered checkbox component.

1. public abstract void itemStateChanged(ItemEvent e);  

Java ItemListener Example


1. import java.awt.*;    
2. import java.awt.event.*;    
3. public class ItemListenerExample implements ItemListener{    
4.     Checkbox checkBox1,checkBox2;  
5.     Label label;  
6.     ItemListenerExample(){    
7.         Frame f= new Frame("CheckBox Example");    
8.         label = new Label();            
9.         label.setAlignment(Label.CENTER);    
10.         label.setSize(400,100);    
11.         checkBox1 = new Checkbox("C++");    
12.         checkBox1.setBounds(100,100, 50,50);    
13.         checkBox2 = new Checkbox("Java");    
14.         checkBox2.setBounds(100,150, 50,50);    
15.         f.add(checkBox1); f.add(checkBox2); f.add(label);    
16.         checkBox1.addItemListener(this);    
17.         checkBox2.addItemListener(this);    
18.         f.setSize(400,400);    
19.         f.setLayout(null);    
20.         f.setVisible(true);    
21.      }    
22.     public void itemStateChanged(ItemEvent e) {      
23.         if(e.getSource()==checkBox1)  
24.             label.setText("C++ Checkbox: "     
25.             + (e.getStateChange()==1?"checked":"unchecked"));   
26.         if(e.getSource()==checkBox2)  
27.         label.setText("Java Checkbox: "     
28.         + (e.getStateChange()==1?"checked":"unchecked"));    
29.      }  
30. public static void main(String args[])    
31. {    
32.     new ItemListenerExample();    
33. }    
34. }    

Output:

Java KeyListener Interface


The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. The KeyListener interface is found in java.awt.event package. It has three
methods.

Methods of KeyListener interface


The signature of 3 methods found in KeyListener interface are given below:

1. public abstract void keyPressed(KeyEvent e);  
2. public abstract void keyReleased(KeyEvent e);  
3. public abstract void keyTyped(KeyEvent e);  

Java KeyListener Example


1. import java.awt.*;  
2. import java.awt.event.*;  
3. public class KeyListenerExample extends Frame implements KeyListener{  
4.     Label l;  
5.     TextArea area;  
6.     KeyListenerExample(){  
7.           
8.         l=new Label();  
9.         l.setBounds(20,50,100,20);  
10.         area=new TextArea();  
11.         area.setBounds(20,80,300, 300);  
12.         area.addKeyListener(this);  
13.           
14.         add(l);add(area);  
15.         setSize(400,400);  
16.         setLayout(null);  
17.         setVisible(true);  
18.     }  
19.     public void keyPressed(KeyEvent e) {  
20.         l.setText("Key Pressed");  
21.     }  
22.     public void keyReleased(KeyEvent e) {  
23.         l.setText("Key Released");  
24.     }  
25.     public void keyTyped(KeyEvent e) {  
26.         l.setText("Key Typed");  
27.     }  
28.   
29.     public static void main(String[] args) {  
30.         new KeyListenerExample();  
31.     }  
32. }  

Output:

Java KeyListener Example 2: Count Words &


Characters
1. import java.awt.*;  
2. import java.awt.event.*;  
3. public class KeyListenerExample extends Frame implements KeyListener{  
4.     Label l;  
5.     TextArea area;  
6.     KeyListenerExample(){  
7.           
8.         l=new Label();  
9.         l.setBounds(20,50,200,20);  
10.         area=new TextArea();  
11.         area.setBounds(20,80,300, 300);  
12.         area.addKeyListener(this);  
13.           
14.         add(l);add(area);  
15.         setSize(400,400);  
16.         setLayout(null);  
17.         setVisible(true);  
18.     }  
19.     public void keyPressed(KeyEvent e) {}  
20.     public void keyReleased(KeyEvent e) {  
21.         String text=area.getText();  
22.         String words[]=text.split("\\s");  
23.         l.setText("Words: "+words.length+" Characters:"+text.length());  
24.     }  
25.     public void keyTyped(KeyEvent e) {}  
26.   
27.     public static void main(String[] args) {  
28.         new KeyListenerExample();  
29.     }  
30. }  

Output:
Java WindowListener Interface
The Java WindowListener is notified whenever you change the state of window. It is notified
against WindowEvent. The WindowListener interface is found in java.awt.event package. It
has three methods.

Methods of WindowListener interface


The signature of 7 methods found in WindowListener interface are given below:

1. public abstract void windowActivated(WindowEvent e);  
2. public abstract void windowClosed(WindowEvent e);  
3. public abstract void windowClosing(WindowEvent e);  
4. public abstract void windowDeactivated(WindowEvent e);  
5. public abstract void windowDeiconified(WindowEvent e);  
6. public abstract void windowIconified(WindowEvent e);  
7. public abstract void windowOpened(WindowEvent e);  

Java WindowListener Example


1. import java.awt.*;  
2. import java.awt.event.WindowEvent;  
3. import java.awt.event.WindowListener;  
4. public class WindowExample extends Frame implements WindowListener{  
5.     WindowExample(){  
6.         addWindowListener(this);  
7.           
8.         setSize(400,400);  
9.         setLayout(null);  
10.         setVisible(true);  
11.     }  
12.       
13. public static void main(String[] args) {  
14.     new WindowExample();  
15. }  
16. public void windowActivated(WindowEvent arg0) {  
17.     System.out.println("activated");  
18. }  
19. public void windowClosed(WindowEvent arg0) {  
20.     System.out.println("closed");  
21. }  
22. public void windowClosing(WindowEvent arg0) {  
23.     System.out.println("closing");  
24.     dispose();  
25. }  
26. public void windowDeactivated(WindowEvent arg0) {  
27.     System.out.println("deactivated");  
28. }  
29. public void windowDeiconified(WindowEvent arg0) {  
30.     System.out.println("deiconified");  
31. }  
32. public void windowIconified(WindowEvent arg0) {  
33.     System.out.println("iconified");  
34. }  
35. public void windowOpened(WindowEvent arg0) {  
36.     System.out.println("opened");  
37. }  
38. }  

Output:

Java WindowListener Interface


The Java WindowListener is notified whenever you change the state of window. It is notified against Win
package. It has three methods.

Methods of WindowListener interface


The signature of 7 methods found in WindowListener interface are given below:

1. public abstract void windowActivated(WindowEvent e);
2. public abstract void windowClosed(WindowEvent e);
3. public abstract void windowClosing(WindowEvent e);
4. public abstract void windowDeactivated(WindowEvent e);
5. public abstract void windowDeiconified(WindowEvent e);
6. public abstract void windowIconified(WindowEvent e);
7. public abstract void windowOpened(WindowEvent e);

Java WindowListener Example


1. import java.awt.*;
2. import java.awt.event.WindowEvent;
3. import java.awt.event.WindowListener;
4. public class WindowExample extends Frame implements WindowListener{
5.     WindowExample(){
6.         addWindowListener(this);
7.
8.         setSize(400,400);
9.         setLayout(null);
10.         setVisible(true);
11.     }
12.
13. public static void main(String[] args) {
14.     new WindowExample();
15. }
16. public void windowActivated(WindowEvent arg0) {
17.     System.out.println("activated");
18. }
19. public void windowClosed(WindowEvent arg0) {
20.     System.out.println("closed");
21. }
22. public void windowClosing(WindowEvent arg0) {
23.     System.out.println("closing");
24.     dispose();
25. }
26. public void windowDeactivated(WindowEvent arg0) {
27.     System.out.println("deactivated");
28. }
29. public void windowDeiconified(WindowEvent arg0) {
30.     System.out.println("deiconified");
31. }
32. public void windowIconified(WindowEvent arg0) {
33.     System.out.println("iconified");
34. }
35. public void windowOpened(WindowEvent arg0) {
36.     System.out.println("opened");
37. }
38. }

Output:

 
Java Adapter Classes
Java adapter classes provide the default implementation of listener interfaces. If you inherit
the adapter class, you will not be forced to provide the implementation of all the methods of
listener interfaces. So it saves code.

The adapter classes are found


in java.awt.event, java.awt.dnd and javax.swing.event packages. The Adapter classes
with their corresponding listener interfaces are given below.

java.awt.event Adapter classes


Java WindowAdapter Example
1. import java.awt.*;  
2. import java.awt.event.*;  
3. public class AdapterExample{  
4.     Frame f;  
5.     AdapterExample(){  
6.         f=new Frame("Window Adapter");  
7.         f.addWindowListener(new WindowAdapter(){  
8.             public void windowClosing(WindowEvent e) {  
9.                 f.dispose();  
10.             }  
11.         });  
12.           
13.         f.setSize(400,400);  
14.         f.setLayout(null);  
15.         f.setVisible(true);  
16.     }  
17. public static void main(String[] args) {  
18.     new AdapterExample();  
19. }  
20. }  

Output:

Java MouseAdapter Example


1. import java.awt.*;  
2. import java.awt.event.*;  
3. public class MouseAdapterExample extends MouseAdapter{  
4.     Frame f;  
5.     MouseAdapterExample(){  
6.         f=new Frame("Mouse Adapter");  
7.         f.addMouseListener(this);  
8.           
9.         f.setSize(300,300);  
10.         f.setLayout(null);  
11.         f.setVisible(true);  
12.     }  
13.     public void mouseClicked(MouseEvent e) {  
14.         Graphics g=f.getGraphics();  
15.         g.setColor(Color.BLUE);  
16.         g.fillOval(e.getX(),e.getY(),30,30);  
17.     }  
18.       
19. public static void main(String[] args) {  
20.     new MouseAdapterExample();  
21. }  
22. }  

Output:

Java MouseMotionAdapter Example


1. import java.awt.*;  
2. import java.awt.event.*;  
3. public class MouseMotionAdapterExample extends MouseMotionAdapter{  
4.     Frame f;  
5.     MouseMotionAdapterExample(){  
6.         f=new Frame("Mouse Motion Adapter");  
7.         f.addMouseMotionListener(this);  
8.           
9.         f.setSize(300,300);  
10.         f.setLayout(null);  
11.         f.setVisible(true);  
12.     }  
13. public void mouseDragged(MouseEvent e) {  
14.     Graphics g=f.getGraphics();  
15.     g.setColor(Color.ORANGE);  
16.     g.fillOval(e.getX(),e.getY(),20,20);  
17. }  
18. public static void main(String[] args) {  
19.     new MouseMotionAdapterExample();  
20. }  
21. }  

Output:

Java KeyAdapter Example


1. import java.awt.*;  
2. import java.awt.event.*;  
3. public class KeyAdapterExample extends KeyAdapter{  
4.     Label l;  
5.     TextArea area;  
6.     Frame f;  
7.     KeyAdapterExample(){  
8.         f=new Frame("Key Adapter");  
9.         l=new Label();  
10.         l.setBounds(20,50,200,20);  
11.         area=new TextArea();  
12.         area.setBounds(20,80,300, 300);  
13.         area.addKeyListener(this);  
14.           
15.         f.add(l);f.add(area);  
16.         f.setSize(400,400);  
17.         f.setLayout(null);  
18.         f.setVisible(true);  
19.     }  
20.     public void keyReleased(KeyEvent e) {  
21.         String text=area.getText();  
22.         String words[]=text.split("\\s");  
23.         l.setText("Words: "+words.length+" Characters:"+text.length());  
24.     }  
25.   
26.     public static void main(String[] args) {  
27.         new KeyAdapterExample();  
28.     }  
29. }  

Output:
How to close AWT Window in Java
We can close the AWT Window or Frame by calling dispose() or System.exit() inside
windowClosing() method. The windowClosing() method is found
in WindowListener interface and WindowAdapter class.

The WindowAdapter class implements WindowListener interfaces. It provides the default


implementation of all the 7 methods of WindowListener interface. To override the
windowClosing() method, you can either use WindowAdapter class or WindowListener
interface.

If you implement the WindowListener interface, you will be forced to override all the 7
methods of WindowListener interface. So it is better to use WindowAdapter class.

Different ways to override windowClosing() method


There are many ways to override windowClosing() method:

o By anonymous class
o By inheriting WindowAdapter class
o By implementing WindowListener interface

Close AWT Window Example 1: Anonymous class


1. import java.awt.*;  
2. import java.awt.event.WindowEvent;  
3. import java.awt.event.WindowListener;  
4. public class WindowExample extends Frame{  
5.     WindowExample(){  
6.         addWindowListener(new WindowAdapter(){  
7.             public void windowClosing(WindowEvent e) {  
8.                 dispose();  
9.             }  
10.         });  
11.         setSize(400,400);  
12.         setLayout(null);  
13.         setVisible(true);  
14.     }  
15. public static void main(String[] args) {  
16.     new WindowExample();  
17. }  

Output:

Close AWT Window Example 2: extending


WindowAdapter
1. import java.awt.*;  
2. import java.awt.event.*;  
3. public class AdapterExample extends WindowAdapter{  
4.     Frame f;  
5.     AdapterExample(){  
6.         f=new Frame();  
7.         f.addWindowListener(this);  
8.           
9.         f.setSize(400,400);  
10.         f.setLayout(null);  
11.         f.setVisible(true);  
12.     }  
13. public void windowClosing(WindowEvent e) {  
14.     f.dispose();  
15. }  
16. public static void main(String[] args) {  
17.     new AdapterExample();  
18. }  
19. }  

Close AWT Window Example 3: implementing


WindowListener
1. import java.awt.*;  
2. import java.awt.event.WindowEvent;  
3. import java.awt.event.WindowListener;  
4. public class WindowExample extends Frame implements WindowListener{  
5.     WindowExample(){  
6.         addWindowListener(this);  
7.           
8.         setSize(400,400);  
9.         setLayout(null);  
10.         setVisible(true);  
11.     }  
12.       
13. public static void main(String[] args) {  
14.     new WindowExample();  
15. }  
16. public void windowActivated(WindowEvent e) {}  
17. public void windowClosed(WindowEvent e) {}  
18. public void windowClosing(WindowEvent e) {  
19.     dispose();  
20. }  
21. public void windowDeactivated(WindowEvent e) {}  
22. public void windowDeiconified(WindowEvent e) {}  
23. public void windowIconified(WindowEvent e) {}  
24. public void windowOpened(WindowEvent arg0) {}  
25. }  
Java Swing
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.
Java Swing Examples
There are two ways to create a frame:

o By creating the object of Frame class (association)


o By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example


Let's see a simple swing example where we are creating one button and adding it on the
JFrame object inside the main() method.

File: FirstSwingExample.java

1. import javax.swing.*;  
2. public class FirstSwingExample {  
3. public static void main(String[] args) {  
4. JFrame f=new JFrame();//creating instance of JFrame  
5.           
6. JButton b=new JButton("click");//creating instance of JButton  
7. b.setBounds(130,100,100, 40);//x axis, y axis, width, height  
8.           
9. f.add(b);//adding button in JFrame  
10.           
11. f.setSize(400,500);//400 width and 500 height  
12. f.setLayout(null);//using no layout managers  
13. f.setVisible(true);//making the frame visible  
14. }  
15. }  
Example of Swing by Association inside constructor
We can also write all the codes of creating JFrame, JButton and method call inside the java
constructor.

File: Simple.java

1. import javax.swing.*;  
2. public class Simple {  
3. JFrame f;  
4. Simple(){  
5. f=new JFrame();//creating instance of JFrame  
6.           
7. JButton b=new JButton("click");//creating instance of JButton  
8. b.setBounds(130,100,100, 40);  
9.           
10. f.add(b);//adding button in JFrame  
11.           
12. f.setSize(400,500);//400 width and 500 height  
13. f.setLayout(null);//using no layout managers  
14. f.setVisible(true);//making the frame visible  
15. }  
16.   
17. public static void main(String[] args) {  
18. new Simple();  
19. }  
20. }  

The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that
sets the position of the button.

Simple example of Swing by inheritance


We can also inherit the JFrame class, so there is no need to create the instance of JFrame
class explicitly.

File: Simple2.java

1. import javax.swing.*;  
2. public class Simple2 extends JFrame{//inheriting JFrame  
3. JFrame f;  
4. Simple2(){  
5. JButton b=new JButton("click");//create button  
6. b.setBounds(130,100,100, 40);  
7.           
8. add(b);//adding button on frame  
9. setSize(400,500);  
10. setLayout(null);  
11. setVisible(true);  
12. }  
13. public static void main(String[] args) {  
14. new Simple2();  
15. }}  

Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.

JButton class declaration


Let's see the declaration for javax.swing.JButton class.

1. public class JButton extends AbstractButton implements Accessible  

Commonly used Constructors:


Java JButton Example
1. import javax.swing.*;    
2. public class ButtonExample {  
3. public static void main(String[] args) {  
4.     JFrame f=new JFrame("Button Example");  
5.     JButton b=new JButton("Click Here");  
6.     b.setBounds(50,100,95,30);  
7.     f.add(b);  
8.     f.setSize(400,400);  
9.     f.setLayout(null);  
10.     f.setVisible(true);   
11. }  
12. }  

Output:

Java JButton Example with ActionListener


1. import java.awt.event.*;  
2. import javax.swing.*;    
3. public class ButtonExample {  
4. public static void main(String[] args) {  
5.     JFrame f=new JFrame("Button Example");  
6.     final JTextField tf=new JTextField();  
7.     tf.setBounds(50,50, 150,20);  
8.     JButton b=new JButton("Click Here");  
9.     b.setBounds(50,100,95,30);  
10.     b.addActionListener(new ActionListener(){  
11. public void actionPerformed(ActionEvent e){  
12.             tf.setText("Welcome to Javatpoint.");  
13.         }  
14.     });  
15.     f.add(b);f.add(tf);  
16.     f.setSize(400,400);  
17.     f.setLayout(null);  
18.     f.setVisible(true);   
19. }  
20. }  

Output:

Example of displaying image on the button:


1. import javax.swing.*;      
2. public class ButtonExample{    
3. ButtonExample(){    
4. JFrame f=new JFrame("Button Example");            
5. JButton b=new JButton(new ImageIcon("D:\\icon.png"));    
6. b.setBounds(100,100,100, 40);    
7. f.add(b);    
8. f.setSize(300,400);    
9. f.setLayout(null);    
10. f.setVisible(true);    
11. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
12.     }         
13. public static void main(String[] args) {    
14.     new ButtonExample();    
15. }    
16. }    

Output:

Java JLabel
The object of JLabel class is a component for placing text in a container. It is used to display
a single line of read only text. The text can be changed by an application but a user cannot
edit it directly. It inherits JComponent class.

JLabel class declaration


Let's see the declaration for javax.swing.JLabel class.

public class JLabel extends JComponent implements SwingConstants, Accessible  
Java JLabel Example
1. import javax.swing.*;  
2. class LabelExample  
3. {  
4. public static void main(String args[])  
5.     {  
6.     JFrame f= new JFrame("Label Example");  
7.     JLabel l1,l2;  
8.     l1=new JLabel("First Label.");  
9.     l1.setBounds(50,50, 100,30);  
10.     l2=new JLabel("Second Label.");  
11.     l2.setBounds(50,100, 100,30);  
12.     f.add(l1); f.add(l2);  
13.     f.setSize(300,300);  
14.     f.setLayout(null);  
15.     f.setVisible(true);  
16.     }  
17.     }  

Output:

Java JLabel Example with ActionListener


1. import javax.swing.*;  
2. import java.awt.*;  
3. import java.awt.event.*;  
4. public class LabelExample extends Frame implements ActionListener{  
5.     JTextField tf; JLabel l; JButton b;  
6.     LabelExample(){  
7.         tf=new JTextField();  
8.         tf.setBounds(50,50, 150,20);  
9.         l=new JLabel();  
10.         l.setBounds(50,100, 250,20);      
11.         b=new JButton("Find IP");  
12.         b.setBounds(50,150,95,30);  
13.         b.addActionListener(this);    
14.         add(b);add(tf);add(l);    
15.         setSize(400,400);  
16.         setLayout(null);  
17.         setVisible(true);  
18.     }  
19.     public void actionPerformed(ActionEvent e) {  
20.         try{  
21.         String host=tf.getText();  
22.         String ip=java.net.InetAddress.getByName(host).getHostAddress();  
23.         l.setText("IP of "+host+" is: "+ip);  
24.         }catch(Exception ex){System.out.println(ex);}  
25.     }  
26.     public static void main(String[] args) {  
27.         new LabelExample();  
28.     } }  

Output:

Java JTextField
The object of a JTextField class is a text component that allows the editing of a single line
text. It inherits JTextComponent class.

JTextField class declaration


Let's see the declaration for javax.swing.JTextField class.

1. public class JTextField extends JTextComponent implements SwingConstants  

Java JTextField Example


1. import javax.swing.*;  
2. class TextFieldExample  
3. {  
4. public static void main(String args[])  
5.     {  
6.     JFrame f= new JFrame("TextField Example");  
7.     JTextField t1,t2;  
8.     t1=new JTextField("Welcome to Javatpoint.");  
9.     t1.setBounds(50,100, 200,30);  
10.     t2=new JTextField("AWT Tutorial");  
11.     t2.setBounds(50,150, 200,30);  
12.     f.add(t1); f.add(t2);  
13.     f.setSize(400,400);  
14.     f.setLayout(null);  
15.     f.setVisible(true);  
16.     }  
17.     }  

Output:

Java JTextField Example with ActionListener


1. import javax.swing.*;  
2. import java.awt.event.*;  
3. public class TextFieldExample implements ActionListener{  
4.     JTextField tf1,tf2,tf3;  
5.     JButton b1,b2;  
6.     TextFieldExample(){  
7.         JFrame f= new JFrame();  
8.         tf1=new JTextField();  
9.         tf1.setBounds(50,50,150,20);  
10.         tf2=new JTextField();  
11.         tf2.setBounds(50,100,150,20);  
12.         tf3=new JTextField();  
13.         tf3.setBounds(50,150,150,20);  
14.         tf3.setEditable(false);   
15.         b1=new JButton("+");  
16.         b1.setBounds(50,200,50,50);  
17.         b2=new JButton("-");  
18.         b2.setBounds(120,200,50,50);  
19.         b1.addActionListener(this);  
20.         b2.addActionListener(this);  
21.         f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);  
22.         f.setSize(300,300);  
23.         f.setLayout(null);  
24.         f.setVisible(true);  
25.     }         
26.     public void actionPerformed(ActionEvent e) {  
27.         String s1=tf1.getText();  
28.         String s2=tf2.getText();  
29.         int a=Integer.parseInt(s1);  
30.         int b=Integer.parseInt(s2);  
31.         int c=0;  
32.         if(e.getSource()==b1){  
33.             c=a+b;  
34.         }else if(e.getSource()==b2){  
35.             c=a-b;  
36.         }  
37.         String result=String.valueOf(c);  
38.         tf3.setText(result);  
39.     }  
40. public static void main(String[] args) {  
41.     new TextFieldExample();  
42. } }  

Output:

Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the editing
of multiple line text. It inherits JTextComponent class

JTextArea class declaration


Let's see the declaration for javax.swing.JTextArea class.

public class JTextArea extends JTextComponent  
Java JTextArea Example
1. import javax.swing.*;  
2. public class TextAreaExample  
3. {  
4.      TextAreaExample(){  
5.         JFrame f= new JFrame();  
6.         JTextArea area=new JTextArea("Welcome to javatpoint");  
7.         area.setBounds(10,30, 200,200);  
8.         f.add(area);  
9.         f.setSize(300,300);  
10.         f.setLayout(null);  
11.         f.setVisible(true);  
12.      }  
13. public static void main(String args[])  
14.     {  
15.    new TextAreaExample();  
16.     }}  

Output:

Java JTextArea Example with ActionListener


1. import javax.swing.*;  
2. import java.awt.event.*;  
3. public class TextAreaExample implements ActionListener{  
4. JLabel l1,l2;  
5. JTextArea area;  
6. JButton b;  
7. TextAreaExample() {  
8.     JFrame f= new JFrame();  
9.     l1=new JLabel();  
10.     l1.setBounds(50,25,100,30);  
11.     l2=new JLabel();  
12.     l2.setBounds(160,25,100,30);  
13.     area=new JTextArea();  
14.     area.setBounds(20,75,250,200);  
15.     b=new JButton("Count Words");  
16.     b.setBounds(100,300,120,30);  
17.     b.addActionListener(this);  
18.     f.add(l1);f.add(l2);f.add(area);f.add(b);  
19.     f.setSize(450,450);  
20.     f.setLayout(null);  
21.     f.setVisible(true);  
22. }  
23. public void actionPerformed(ActionEvent e){  
24.     String text=area.getText();  
25.     String words[]=text.split("\\s");  
26.     l1.setText("Words: "+words.length);  
27.     l2.setText("Characters: "+text.length());  
28. }  
29. public static void main(String[] args) {  
30.     new TextAreaExample();  
31. }  
32. }  

Output:
Java JPasswordField
The object of a JPasswordField class is a text component specialized for password entry. It
allows the editing of a single line of text. It inherits JTextField class.

JPasswordField class declaration


Let's see the declaration for javax.swing.JPasswordField class.

1. public class JPasswordField extends JTextField  
Java JPasswordField Example
1. import javax.swing.*;    
2. public class PasswordFieldExample {  
3.     public static void main(String[] args) {    
4.     JFrame f=new JFrame("Password Field Example");    
5.      JPasswordField value = new JPasswordField();   
6.      JLabel l1=new JLabel("Password:");    
7.         l1.setBounds(20,100, 80,30);    
8.          value.setBounds(100,100,100,30);    
9.             f.add(value);  f.add(l1);  
10.             f.setSize(300,300);    
11.             f.setLayout(null);    
12.             f.setVisible(true);     
13. }  
14. }  

Output:
Java JPasswordField Example with ActionListener
1. import javax.swing.*;    
2. import java.awt.event.*;  
3. public class PasswordFieldExample {  
4.     public static void main(String[] args) {    
5.     JFrame f=new JFrame("Password Field Example");    
6.      final JLabel label = new JLabel();            
7.      label.setBounds(20,150, 200,50);  
8.      final JPasswordField value = new JPasswordField();   
9.      value.setBounds(100,75,100,30);   
10.      JLabel l1=new JLabel("Username:");    
11.         l1.setBounds(20,20, 80,30);    
12.         JLabel l2=new JLabel("Password:");    
13.         l2.setBounds(20,75, 80,30);    
14.         JButton b = new JButton("Login");  
15.         b.setBounds(100,120, 80,30);    
16.         final JTextField text = new JTextField();  
17.         text.setBounds(100,20, 100,30);    
18.                 f.add(value); f.add(l1); f.add(label); f.add(l2); f.add(b); f.add(text);  
19.                 f.setSize(300,300);    
20.                 f.setLayout(null);    
21.                 f.setVisible(true);     
22.                 b.addActionListener(new ActionListener() {  
23.                 public void actionPerformed(ActionEvent e) {       
24.                    String data = "Username " + text.getText();  
25.                    data += ", Password: "   
26.                    + new String(value.getPassword());   
27.                    label.setText(data);          
28.                 }  
29.              });   
30. }  
31. }  

Output:

Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or
off (false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on
".It inherits JToggleButton class.

JCheckBox class declaration


Let's see the declaration for javax.swing.JCheckBox class.
1. public class JCheckBox extends JToggleButton implements Accessible  

Java JCheckBox Example


1. import javax.swing.*;  
2. public class CheckBoxExample  
3. {  
4.      CheckBoxExample(){  
5.         JFrame f= new JFrame("CheckBox Example");  
6.         JCheckBox checkBox1 = new JCheckBox("C++");  
7.         checkBox1.setBounds(100,100, 50,50);  
8.         JCheckBox checkBox2 = new JCheckBox("Java", true);  
9.         checkBox2.setBounds(100,150, 50,50);  
10.         f.add(checkBox1);  
11.         f.add(checkBox2);  
12.         f.setSize(400,400);  
13.         f.setLayout(null);  
14.         f.setVisible(true);  
15.      }  
16. public static void main(String args[])  
17.     {  
18.     new CheckBoxExample();  
19.     }}  

Output:

Java JCheckBox Example with ItemListener


1. import javax.swing.*;  
2. import java.awt.event.*;    
3. public class CheckBoxExample    
4. {    
5.      CheckBoxExample(){    
6.         JFrame f= new JFrame("CheckBox Example");    
7.         final JLabel label = new JLabel();            
8.         label.setHorizontalAlignment(JLabel.CENTER);    
9.         label.setSize(400,100);    
10.         JCheckBox checkbox1 = new JCheckBox("C++");    
11.         checkbox1.setBounds(150,100, 50,50);    
12.         JCheckBox checkbox2 = new JCheckBox("Java");    
13.         checkbox2.setBounds(150,150, 50,50);    
14.         f.add(checkbox1); f.add(checkbox2); f.add(label);    
15.         checkbox1.addItemListener(new ItemListener() {    
16.              public void itemStateChanged(ItemEvent e) {                 
17.                 label.setText("C++ Checkbox: "     
18.                 + (e.getStateChange()==1?"checked":"unchecked"));    
19.              }    
20.           });    
21.         checkbox2.addItemListener(new ItemListener() {    
22.              public void itemStateChanged(ItemEvent e) {                 
23.                 label.setText("Java Checkbox: "     
24.                 + (e.getStateChange()==1?"checked":"unchecked"));    
25.              }    
26.           });    
27.         f.setSize(400,400);    
28.         f.setLayout(null);    
29.         f.setVisible(true);    
30.      }    
31. public static void main(String args[])    
32. {    
33.     new CheckBoxExample();    
34. }    
35. }    

Output:
Java JCheckBox Example: Food Order
1. import javax.swing.*;  
2. import java.awt.event.*;  
3. public class CheckBoxExample extends JFrame implements ActionListener{  
4.     JLabel l;  
5.     JCheckBox cb1,cb2,cb3;  
6.     JButton b;  
7.     CheckBoxExample(){  
8.         l=new JLabel("Food Ordering System");  
9.         l.setBounds(50,50,300,20);  
10.         cb1=new JCheckBox("Pizza @ 100");  
11.         cb1.setBounds(100,100,150,20);  
12.         cb2=new JCheckBox("Burger @ 30");  
13.         cb2.setBounds(100,150,150,20);  
14.         cb3=new JCheckBox("Tea @ 10");  
15.         cb3.setBounds(100,200,150,20);  
16.         b=new JButton("Order");  
17.         b.setBounds(100,250,80,30);  
18.         b.addActionListener(this);  
19.         add(l);add(cb1);add(cb2);add(cb3);add(b);  
20.         setSize(400,400);  
21.         setLayout(null);  
22.         setVisible(true);  
23.         setDefaultCloseOperation(EXIT_ON_CLOSE);  
24.     }  
25.     public void actionPerformed(ActionEvent e){  
26.         float amount=0;  
27.         String msg="";  
28.         if(cb1.isSelected()){  
29.             amount+=100;  
30.             msg="Pizza: 100\n";  
31.         }  
32.         if(cb2.isSelected()){  
33.             amount+=30;  
34.             msg+="Burger: 30\n";  
35.         }  
36.         if(cb3.isSelected()){  
37.             amount+=10;  
38.             msg+="Tea: 10\n";  
39.         }  
40.         msg+="-----------------\n";  
41.         JOptionPane.showMessageDialog(this,msg+"Total: "+amount);  
42.     }  
43.     public static void main(String[] args) {  
44.         new CheckBoxExample();  
45.     }  
46. }  

Output:
 

Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz.

It should be added in ButtonGroup to select one radio button only.


JRadioButton class declaration
Let's see the declaration for javax.swing.JRadioButton class.

public class JRadioButton extends JToggleButton implements Accessible  

Java JRadioButton Example


1. import javax.swing.*;    
2. public class RadioButtonExample {    
3. JFrame f;    
4. RadioButtonExample(){    
5. f=new JFrame();     
6. JRadioButton r1=new JRadioButton("A) Male");    
7. JRadioButton r2=new JRadioButton("B) Female");    
8. r1.setBounds(75,50,100,30);    
9. r2.setBounds(75,100,100,30);    
10. ButtonGroup bg=new ButtonGroup();    
11. bg.add(r1);bg.add(r2);    
12. f.add(r1);f.add(r2);      
13. f.setSize(300,300);    
14. f.setLayout(null);    
15. f.setVisible(true);    
16. }    
17. public static void main(String[] args) {    
18.     new RadioButtonExample();    
19. }    
20. }    

Output:

Java JRadioButton Example with ActionListener


1. import javax.swing.*;    
2. import java.awt.event.*;    
3. class RadioButtonExample extends JFrame implements ActionListener{    
4. JRadioButton rb1,rb2;    
5. JButton b;    
6. RadioButtonExample(){      
7. rb1=new JRadioButton("Male");    
8. rb1.setBounds(100,50,100,30);      
9. rb2=new JRadioButton("Female");    
10. rb2.setBounds(100,100,100,30);    
11. ButtonGroup bg=new ButtonGroup();    
12. bg.add(rb1);bg.add(rb2);    
13. b=new JButton("click");    
14. b.setBounds(100,150,80,30);    
15. b.addActionListener(this);    
16. add(rb1);add(rb2);add(b);    
17. setSize(300,300);    
18. setLayout(null);    
19. setVisible(true);    
20. }    
21. public void actionPerformed(ActionEvent e){    
22. if(rb1.isSelected()){    
23. JOptionPane.showMessageDialog(this,"You are Male.");    
24. }    
25. if(rb2.isSelected()){    
26. JOptionPane.showMessageDialog(this,"You are Female.");    
27. }    
28. }    
29. public static void main(String args[]){    
30. new RadioButtonExample();    
31. }}   

Output:
Java JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user
is shown on the top of a menu. It inherits JComponent class.

JComboBox class declaration


Let's see the declaration for javax.swing.JComboBox class.

1. public class JComboBox extends JComponent implements ItemSelectable, ListDataListen
er, ActionListener, Accessible  
Java JComboBox Example
1. import javax.swing.*;    
2. public class ComboBoxExample {    
3. JFrame f;    
4. ComboBoxExample(){    
5.     f=new JFrame("ComboBox Example");    
6.     String country[]={"India","Aus","U.S.A","England","Newzealand"};        
7.     JComboBox cb=new JComboBox(country);    
8.     cb.setBounds(50, 50,90,20);    
9.     f.add(cb);        
10.     f.setLayout(null);    
11.     f.setSize(400,500);    
12.     f.setVisible(true);         
13. }    
14. public static void main(String[] args) {    
15.     new ComboBoxExample();         
16. }    
17. }   

Output:

Java JComboBox Example with ActionListener


1. import javax.swing.*;    
2. import java.awt.event.*;    
3. public class ComboBoxExample {    
4. JFrame f;    
5. ComboBoxExample(){    
6.     f=new JFrame("ComboBox Example");   
7.     final JLabel label = new JLabel();          
8.     label.setHorizontalAlignment(JLabel.CENTER);  
9.     label.setSize(400,100);  
10.     JButton b=new JButton("Show");  
11.     b.setBounds(200,100,75,20);  
12.     String languages[]={"C","C++","C#","Java","PHP"};        
13.     final JComboBox cb=new JComboBox(languages);    
14.     cb.setBounds(50, 100,90,20);    
15.     f.add(cb); f.add(label); f.add(b);    
16.     f.setLayout(null);    
17.     f.setSize(350,350);    
18.     f.setVisible(true);       
19.     b.addActionListener(new ActionListener() {  
20.         public void actionPerformed(ActionEvent e) {       
21. String data = "Programming language Selected: "   
22.    + cb.getItemAt(cb.getSelectedIndex());  
23. label.setText(data);  
24. }  
25. });           
26. }    
27. public static void main(String[] args) {    
28.     new ComboBoxExample();         
29. }    
30. }    

Output:

Java JTable
The JTable class is used to display data in tabular form. It is composed of rows and
columns.

JTable class declaration


Let's see the declaration for javax.swing.JTable class.
Java JTable Example
1. import javax.swing.*;    
2. public class TableExample {    
3.     JFrame f;    
4.     TableExample(){    
5.     f=new JFrame();    
6.     String data[][]={ {"101","Amit","670000"},    
7.                           {"102","Jai","780000"},    
8.                           {"101","Sachin","700000"}};    
9.     String column[]={"ID","NAME","SALARY"};         
10.     JTable jt=new JTable(data,column);    
11.     jt.setBounds(30,40,200,300);          
12.     JScrollPane sp=new JScrollPane(jt);    
13.     f.add(sp);          
14.     f.setSize(300,400);    
15.     f.setVisible(true);    
16. }     
17. public static void main(String[] args) {    
18.     new TableExample();    
19. }    
20. }  
Output:

Java JTable Example with ListSelectionListener


1. import javax.swing.*;    
2. import javax.swing.event.*;  
3. public class TableExample {    
4.       public static void main(String[] a) {  
5.             JFrame f = new JFrame("Table Example");  
6.             String data[][]={ {"101","Amit","670000"},    
7.                                                                        {"102","Jai","780000"},    
8.                                                                        {"101","Sachin","700000"}};    
9.                             String column[]={"ID","NAME","SALARY"};         
10.                             final JTable jt=new JTable(data,column);    
11.             jt.setCellSelectionEnabled(true);  
12.             ListSelectionModel select= jt.getSelectionModel();  
13.             select.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  
14.             select.addListSelectionListener(new ListSelectionListener() {  
15.               public void valueChanged(ListSelectionEvent e) {  
16.                 String Data = null;  
17.                 int[] row = jt.getSelectedRows();  
18.                 int[] columns = jt.getSelectedColumns();  
19.                 for (int i = 0; i < row.length; i++) {  
20.                   for (int j = 0; j < columns.length; j++) {  
21.                     Data = (String) jt.getValueAt(row[i], columns[j]);  
22.                   } }  
23.                 System.out.println("Table element selected is: " + Data);    
24.               }       
25.             });  
26.             JScrollPane sp=new JScrollPane(jt);    
27.             f.add(sp);  
28.             f.setSize(300, 200);  
29.             f.setVisible(true);  
30.           }  
31.         }  

Output:

If you select an element in column NAME, name of the element will be displayed on the
console:

1. Table element selected is: Sachin  

Java JList
The object of JList class represents a list of text items. The list of text items can be set up
so that the user can choose either one item or multiple items. It inherits JComponent class.

JList class declaration


Let's see the declaration for javax.swing.JList class.
1. public class JList extends JComponent implements Scrollable, Accessible  

Java JList Example


1. import javax.swing.*;  
2. public class ListExample  
3. {  
4.      ListExample(){  
5.         JFrame f= new JFrame();  
6.         DefaultListModel<String> l1 = new DefaultListModel<>();  
7.           l1.addElement("Item1");  
8.           l1.addElement("Item2");  
9.           l1.addElement("Item3");  
10.           l1.addElement("Item4");  
11.           JList<String> list = new JList<>(l1);  
12.           list.setBounds(100,100, 75,75);  
13.           f.add(list);  
14.           f.setSize(400,400);  
15.           f.setLayout(null);  
16.           f.setVisible(true);  
17.      }  
18. public static void main(String args[])  
19.     {  
20.    new ListExample();  
21.     }}  

Output:

Java JList Example with ActionListener


1. import javax.swing.*;  
2. import java.awt.event.*;  
3. public class ListExample  
4. {  
5.      ListExample(){  
6.         JFrame f= new JFrame();  
7.         final JLabel label = new JLabel();          
8.         label.setSize(500,100);  
9.         JButton b=new JButton("Show");  
10.         b.setBounds(200,150,80,30);  
11.         final DefaultListModel<String> l1 = new DefaultListModel<>();  
12.           l1.addElement("C");  
13.           l1.addElement("C++");  
14.           l1.addElement("Java");  
15.           l1.addElement("PHP");  
16.           final JList<String> list1 = new JList<>(l1);  
17.           list1.setBounds(100,100, 75,75);  
18.           DefaultListModel<String> l2 = new DefaultListModel<>();  
19.           l2.addElement("Turbo C++");  
20.           l2.addElement("Struts");  
21.           l2.addElement("Spring");  
22.           l2.addElement("YII");  
23.           final JList<String> list2 = new JList<>(l2);  
24.           list2.setBounds(100,200, 75,75);  
25.           f.add(list1); f.add(list2); f.add(b); f.add(label);  
26.           f.setSize(450,450);  
27.           f.setLayout(null);  
28.           f.setVisible(true);  
29.           b.addActionListener(new ActionListener() {  
30.               public void actionPerformed(ActionEvent e) {   
31.                  String data = "";  
32.                  if (list1.getSelectedIndex() != -1) {                       
33.                     data = "Programming language Selected: " + list1.getSelectedValue();   
34.                     label.setText(data);  
35.                  }  
36.                  if(list2.getSelectedIndex() != -1){  
37.                     data += ", FrameWork Selected: ";  
38.                     for(Object frame :list2.getSelectedValues()){  
39.                        data += frame + " ";  
40.                     }  
41.                  }  
42.                  label.setText(data);  
43.               }  
44.            });   
45.      }  
46. public static void main(String args[])  
47.     {  
48.    new ListExample();  
49.     }}  

Output:

Java JOptionPane
The JOptionPane class is used to provide standard dialog boxes such as message dialog box,
confirm dialog box and input dialog box. These dialog boxes are used to display information
or get input from the user. The JOptionPane class inherits JComponent class.

JOptionPane class declaration


1. public class JOptionPane extends JComponent implements Accessible  
Java JOptionPane Example: showMessageDialog()
1. import javax.swing.*;  
2. public class OptionPaneExample {  
3. JFrame f;  
4. OptionPaneExample(){  
5.     f=new JFrame();  
6.     JOptionPane.showMessageDialog(f,"Hello, Welcome to Javatpoint.");  
7. }  
8. public static void main(String[] args) {  
9.     new OptionPaneExample();  
10. }  
11. }  

Output:

Java JOptionPane Example: showMessageDialog()


1. import javax.swing.*;  
2. public class OptionPaneExample {  
3. JFrame f;  
4. OptionPaneExample(){  
5.     f=new JFrame();  
6.     JOptionPane.showMessageDialog(f,"Successfully Updated.","Alert",JOptionPane.WARNING
_MESSAGE);     
7. }  
8. public static void main(String[] args) {  
9.     new OptionPaneExample();  
10. }  
11. }  

Output:
Java JOptionPane Example: showInputDialog()
1. import javax.swing.*;  
2. public class OptionPaneExample {  
3. JFrame f;  
4. OptionPaneExample(){  
5.     f=new JFrame();   
6.     String name=JOptionPane.showInputDialog(f,"Enter Name");      
7. }  
8. public static void main(String[] args) {  
9.     new OptionPaneExample();  
10. }  
11. }  

Output:

Java JOptionPane Example: showConfirmDialog()


1. import javax.swing.*;  
2. import java.awt.event.*;  
3. public class OptionPaneExample extends WindowAdapter{  
4. JFrame f;  
5. OptionPaneExample(){  
6.     f=new JFrame();   
7.     f.addWindowListener(this);  
8.     f.setSize(300, 300);  
9.     f.setLayout(null);  
10.     f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);  
11.     f.setVisible(true);  
12. }  
13. public void windowClosing(WindowEvent e) {  
14.     int a=JOptionPane.showConfirmDialog(f,"Are you sure?");  
15. if(a==JOptionPane.YES_OPTION){  
16.     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
17. }  
18. }  
19. public static void main(String[] args) {  
20.     new  OptionPaneExample();  
21. }     
22. }  

Output:
JAVA APPLETS
All of the preceding examples learned so far are console based applications. 

Applets are small Internet-based programs written in Java and can be downloaded
by any computer. 

The applet is usually embedded in an HTML page on a Web site and can be
executed from within a browser.

An applet must be a subclass of the java.applet.Applet class.

The Applet class provides the standard interface between the applet and the
browser environment.

Swing provides a special subclass of the Applet class called javax.swing.JApplet. 

The JApplet class should be used for all applets that use Swing components to
construct their graphical user interfaces (GUIs).

Benefits of Java Applets

They are very secure.

It works at client side so less response time.

Applets can be executed by browsers running under different platforms.

Note: One disadvantage of Applets is that plugins are required at the client

browser for executing applets

Life Cycle of Java Applets

An applet undergoes various stages between its creation of objects and object
removal as the work of the applet will get done.

Each state of the life cycle is signified by methods.


There are five states (methods) in the life of applet execution.

init () method: intended for whatever initialization needed for the applet

start () method: automatically called after the browser calls the init method or
when a user returns to the page containing the applet.

paint () method: invoked immediately after the start method, and also anytime the
applet needs repaint itself in the browser.

stop () method: automatically called when user moves off the page on which the
applet sits.

destroy () method: Only called when the browser shuts down normally.

Sample creation of a java applet

import java.applet.*;

import java.awt.*;

public class HelloWorld Applet extends Applet{

public void paint (Graphics g){

g.drawString ("Hello World",25,50);

Now create an HTML File that Includes the Applet.

<html>

<head>

<TITLE> A Simple Program </TITLE>

</head>

<body>

Here is the output of my program:


<applet code="HelloWorld.class" width="150"
height="25"></applet>

</body>

</html>

You might also like