Java AWT Tutorial


Java AWT (Abstract Window Toolkit) is an API to create GUI or window-based applications in java.

Java AWT components are platform components for example according are shown by the perspective on operating system. AWT is heavyweight for example its parts are utilizing the assets of OS.

The java.awt package gives classes to AWT api interface, for example, TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy

Container

The Container is a part in AWT that can contain another components like buttons, textfields, names and labels etc. The classes that expands Container class are referred to as holder, for example, Frame, Dialog and Panel.


Window

The window is the compartment that have no borders and menu bars. You must utilize frame, dialog or another window for making a window.


Panel

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

Java AWT Example

Useful Methods of Component class

MethodDescription
public void add(Component c)inserts a part 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 format administrator for the component.
public void setVisible(boolean status)changes the visibility of the part, 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)

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

  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. }}  





javacodegeeks is optimized for learning.© javacodegeeks .
All Right Reserved and you agree to have read and accepted our term and condition