Java AWT Tutorial


Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based application 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 uses the resources of system.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.

JAVA




Java AWT Hierarchy
The hierarchy of Java AWT classes are given below.
hierarchy of awt


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.


Useful Methods of Component class
Method
Description
public void add(Component c)
inserts a component on this component.
public void setSize(int width,int height)
sets the size (width and height) of the component.
public void setLayout(LayoutManager m)
defines the layout manager for the component.
public void setVisible(boolean status)
changes the visibility of the component, by default false.
Java AWT Example
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
  • By extending Frame class (inheritance)
  • By creating the object of Frame class (association)


Simple example of AWT by inheritance
  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.   
  7. add(b);//adding button into frame  
  8. setSize(300,300);//frame size 300 width and 300 height  
  9. setLayout(null);//no layout manager  
  10. setVisible(true);//now frame will be visible, by default not visible  
  11. }  
  12. public static void main(String args[]){  
  13. First f=new First();  
  14. }}  
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


Simple example of AWT by association
  1. import java.awt.*;  
  2. class First2{  
  3. First2(){  
  4. Frame f=new Frame();  
  5.   
  6. Button b=new Button("click me");  
  7. b.setBounds(30,50,80,30);  
  8.   
  9. f.add(b);  
  10. f.setSize(300,300);  
  11. f.setLayout(null);  
  12. f.setVisible(true);  
  13. }  
  14. public static void main(String args[]){  
  15. First2 f=new First2();  
  16. }}  
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. The java.awt.event package provides many event classes and Listener interfaces for event handling.
Event classes and Listener interfaces:
Event Classes
Listener Interfaces
ActionEvent
ActionListener
MouseEvent
MouseListener and MouseMotionListener
MouseWheelEvent
MouseWheelListener
KeyEvent
KeyListener
ItemEvent
ItemListener
TextEvent
TextListener
AdjustmentEvent
AdjustmentListener
WindowEvent
WindowListener
ComponentEvent
ComponentListener
ContainerEvent
ContainerListener
FocusEvent
FocusListener
Steps to perform Event Handling
Following steps are required to perform event handling:
  1. Implement the Listener interface and overrides its methods
  2. Register the component with the Listener


For registering the component with the Listener, many classes provide the registration methods. For example:
  • Button
    • public void addActionListener(ActionListener a){}
  • MenuItem
    • public void addActionListener(ActionListener a){}
  • TextField
    • public void addActionListener(ActionListener a){}
    • public void addTextListener(TextListener a){}
  • TextArea
    • public void addTextListener(TextListener a){}
  • Checkbox
    • public void addItemListener(ItemListener a){}
  • Choice
    • public void addItemListener(ItemListener a){}
  • List
    • public void addActionListener(ActionListener a){}
    • public void addItemListener(ItemListener a){}


EventHandling Codes:
We can put the event handling code into one of the following places:
  1. Same class
  2. Other class
  3. Annonymous class
Example of event handling within class:
  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3.   
  4. class AEvent extends Frame implements ActionListener{  
  5. TextField tf;  
  6. AEvent(){  
  7.   
  8. tf=new TextField();  
  9. tf.setBounds(60,50,170,20);  
  10.   
  11. Button b=new Button("click me");  
  12. b.setBounds(100,120,80,30);  
  13.   
  14. b.addActionListener(this);  
  15.   
  16. add(b);add(tf);  
  17.   
  18. setSize(300,300);  
  19. setLayout(null);  
  20. setVisible(true);  
  21.   
  22. }  
  23.   
  24. public void actionPerformed(ActionEvent e){  
  25. tf.setText("Welcome");  
  26. }  
  27.   
  28. public static void main(String args[]){  
  29. new AEvent();  
  30. }  
  31. }  
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.
event handling in java


2) Example of 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.   
  7. tf=new TextField();  
  8. tf.setBounds(60,50,170,20);  
  9.   
  10. Button b=new Button("click me");  
  11. b.setBounds(100,120,80,30);  
  12.   
  13. Outer o=new Outer(this);  
  14. b.addActionListener(o);//passing outer class instance  
  15.   
  16. add(b);add(tf);  
  17.   
  18. setSize(300,300);  
  19. setLayout(null);  
  20. setVisible(true);  
  21. }  
  22. public static void main(String args[]){  
  23. new AEvent2();  
  24. }  
  25. }  
  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) Example of event handling by Annonymous 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 Swing Tutorial

Java Swing tutorial 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.

Difference between AWT and Swing

There are many differences between java awt and swing that are given below.
No.
Java AWT
Java Swing
1)
AWT components are platform-dependent.
Java swing components are platform-independent.
2)
AWT components are heavyweight.
Swing components are lightweight.
3)
AWT doesn't support pluggable look and feel.
Swing supports pluggable look and feel.
4)
AWT provides less components than Swing.
Swing provides more powerful components such as tables, lists, scrollpanes, colorchooser, tabbedpane etc.
5)
AWT doesn't follows MVC(Model View Controller) where model represents data, view represents presentation and controller acts as an interface between model and view.
Swing follows MVC.

What is JFC

The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop applications.
Do You Know
  • How to create runnable jar file in java?
  • How to display image on a button in swing?
  • How to change the component color by choosing a color from ColorChooser ?
  • How to display the digital watch in swing tutorial ?
  • How to create a notepad in swing?
  • How to create puzzle game and pic puzzle game in swing ?
  • How to create tic tac toe game in swing ?

Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.
hierarchy of javax swing

Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.
Method
Description
public void add(Component c)
add a component on another component.
public void setSize(int width,int height)
sets size of the component.
public void setLayout(LayoutManager m)
sets the layout manager for the component.
public void setVisible(boolean b)
sets the visibility of the component. It is by default false.

Java Swing Examples

There are two ways to create a frame:
  • By creating the object of Frame class (association)
  • 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,10040);//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. }  
simple example of java swing

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,10040);  
  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,10040);  
  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. }}  

JButton class:

The JButton class is used to create a button that have plateform-independent implementation.

Commonly used Constructors:

  • JButton(): creates a button with no text and icon.
  • JButton(String s): creates a button with the specified text.
  • JButton(Icon i): creates a button with the specified icon object.

Commonly used Methods of AbstractButton class:

1) public void setText(String s): is used to set specified text on button.
2) public String getText(): is used to return the text of the button.
3) public void setEnabled(boolean b): is used to enable or disable the button.
4) public void setIcon(Icon b): is used to set the specified Icon on the button.
5) public Icon getIcon(): is used to get the Icon of the button.
6) public void setMnemonic(int a): is used to set the mnemonic on the button.
7) public void addActionListener(ActionListener a): is used to add the action listener to this object.

Note: The JButton class extends AbstractButton class.

Example of displaying image on the button:

  1. import java.awt.event.*;  
  2. import javax.swing.*;  
  3.   
  4. public class ImageButton{  
  5. ImageButton(){  
  6. JFrame f=new JFrame();  
  7.                   
  8.           
  9. JButton b=new JButton(new ImageIcon("b.jpg"));  
  10. b.setBounds(130,100,10040);  
  11.       
  12. f.add(b);  
  13.           
  14. f.setSize(300,400);  
  15. f.setLayout(null);  
  16. f.setVisible(true);  
  17.           
  18. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  19.           
  20.     }  
  21.       
  22. public static void main(String[] args) {  
  23.     new ImageButton();  
  24. }  


  25. }  

JRadioButton class

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.

Commonly used Constructors of JRadioButton class:

  • JRadioButton(): creates an unselected radio button with no text.
  • JRadioButton(String s): creates an unselected radio button with specified text.
  • JRadioButton(String s, boolean selected): creates a radio button with the specified text and selected status.

Commonly used Methods of AbstractButton class:

1) public void setText(String s): is used to set specified text on button.
2) public String getText(): is used to return the text of the button.
3) public void setEnabled(boolean b): is used to enable or disable the button.
4) public void setIcon(Icon b): is used to set the specified Icon on the button.
5) public Icon getIcon(): is used to get the Icon of the button.
6) public void setMnemonic(int a): is used to set the mnemonic on the button.
7) public void addActionListener(ActionListener a): is used to add the action listener to this object.

Note: The JRadioButton class extends the JToggleButton class that extends AbstractButton class.

Example of JRadioButton class:

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

ButtonGroup class:

The ButtonGroup class can be used to group multiple buttons so that at a time only one button can be selected.

JRadioButton example with event handling

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


JTextArea class (Swing Tutorial):
The JTextArea class is used to create a text area. It is a multiline area that displays the plain text only.
Commonly used Constructors:
  • JTextArea(): creates a text area that displays no text initially.
  • JTextArea(String s): creates a text area that displays specified text initially.
  • JTextArea(int row, int column): creates a text area with the specified number of rows and columns that displays no text initially..
  • JTextArea(String s, int row, int column): creates a text area with the specified number of rows and columns that displays specified text.
Commonly used methods of JTextArea class:
1) public void setRows(int rows): is used to set specified number of rows.
2) public void setColumns(int cols):: is used to set specified number of columns.
3) public void setFont(Font f): is used to set the specified font.
4) public void insert(String s, int position): is used to insert the specified text on the specified position.
5) public void append(String s): is used to append the given text to the end of the document.
Example of JTextField class:
  1. import java.awt.Color;  
  2. import javax.swing.*;  
  3.   
  4. public class TArea {  
  5.     JTextArea area;  
  6.     JFrame f;  
  7.     TArea(){  
  8.     f=new JFrame();  
  9.           
  10.     area=new JTextArea(300,300);  
  11.     area.setBounds(10,30,300,300);  
  12.       
  13.     area.setBackground(Color.black);  
  14.     area.setForeground(Color.white);  
  15.           
  16.     f.add(area);  
  17.       
  18.     f.setSize(400,400);  
  19.     f.setLayout(null);  
  20.     f.setVisible(true);  
  21. }  
  22.     public static void main(String[] args) {  
  23.         new TArea();  
  24.     }  


  25. }
JComboBox class:
The JComboBox class is used to create the combobox (drop-down list). At a time only one item can be selected from the item list.
Commonly used Constructors of JComboBox class:
JComboBox()
JComboBox(Object[] items)
JComboBox(Vector<?> items)
Commonly used methods of JComboBox class:
1) public void addItem(Object anObject): is used to add an item to the item list.
2) public void removeItem(Object anObject): is used to delete an item to the item list.
3) public void removeAllItems(): is used to remove all the items from the list.
4) public void setEditable(boolean b): is used to determine whether the JComboBox is editable.
5) public void addActionListener(ActionListener a): is used to add the ActionListener.
6) public void addItemListener(ItemListener i): is used to add the ItemListener.
Example of JComboBox class:
  1. import javax.swing.*;  
  2. public class Combo {  
  3. JFrame f;  
  4. Combo(){  
  5.     f=new JFrame("Combo ex");  
  6.       
  7.     String country[]={"India","Aus","U.S.A","England","Newzeland"};  
  8.       
  9.     JComboBox cb=new JComboBox(country);  
  10.     cb.setBounds(50, 50,90,20);  
  11.     f.add(cb);  
  12.       
  13.     f.setLayout(null);  
  14.     f.setSize(400,500);  
  15.     f.setVisible(true);  
  16.       
  17. }  
  18. public static void main(String[] args) {  
  19.     new Combo();  
  20.       
  21. }  


  22. }  

JTable class (Swing Tutorial):
The JTable class is used to display the data on two dimensional tables of cells.
Commonly used Constructors of JTable class:
  • JTable(): creates a table with empty cells.
  • JTable(Object[][] rows, Object[] columns): creates a table with the specified data.
Example of JTable class:
  1. import javax.swing.*;  
  2. public class MyTable {  
  3.     JFrame f;  
  4. MyTable(){  
  5.     f=new JFrame();  
  6.       
  7.     String data[][]={ {"101","Amit","670000"},  
  8.               {"102","Jai","780000"},  
  9.                           {"101","Sachin","700000"}};  
  10.     String column[]={"ID","NAME","SALARY"};  
  11.       
  12.     JTable jt=new JTable(data,column);  
  13.     jt.setBounds(30,40,200,300);  
  14.       
  15.     JScrollPane sp=new JScrollPane(jt);  
  16.     f.add(sp);  
  17.       
  18.     f.setSize(300,400);  
  19. //  f.setLayout(null);  
  20.     f.setVisible(true);  
  21. }  
  22. public static void main(String[] args) {  
  23.     new MyTable();  
  24. }  
  25. }  
  


Post a Comment

0 Comments