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 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.
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
-
import java.awt.*;
-
class First extends Frame{
-
First(){
-
Button b=new Button("click me");
-
b.setBounds(30,100,80,30);// setting button position
-
-
add(b);//adding button into frame
-
setSize(300,300);//frame size 300 width and 300 height
-
setLayout(null);//no layout manager
-
setVisible(true);//now frame will be visible, by default not visible
-
}
-
public static void main(String args[]){
-
First f=new First();
-
}}
download this example
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.
Simple example of AWT by association
-
import java.awt.*;
-
class First2{
-
First2(){
-
Frame f=new Frame();
-
-
Button b=new Button("click me");
-
b.setBounds(30,50,80,30);
-
-
f.add(b);
-
f.setSize(300,300);
-
f.setLayout(null);
-
f.setVisible(true);
-
}
-
public static void main(String args[]){
-
First2 f=new First2();
-
}}
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:
-
Implement the Listener interface and overrides its methods
-
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:
-
Same class
-
Other class
-
Annonymous class
|
Example of event handling within class:
-
import java.awt.*;
-
import java.awt.event.*;
-
-
class AEvent extends Frame implements ActionListener{
-
TextField tf;
-
AEvent(){
-
-
tf=new TextField();
-
tf.setBounds(60,50,170,20);
-
-
Button b=new Button("click me");
-
b.setBounds(100,120,80,30);
-
-
b.addActionListener(this);
-
-
add(b);add(tf);
-
-
setSize(300,300);
-
setLayout(null);
-
setVisible(true);
-
-
}
-
-
public void actionPerformed(ActionEvent e){
-
tf.setText("Welcome");
-
}
-
-
public static void main(String args[]){
-
new AEvent();
-
}
-
}
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) Example of event handling by Outer class:
-
import java.awt.*;
-
import java.awt.event.*;
-
class AEvent2 extends Frame{
-
TextField tf;
-
AEvent2(){
-
-
tf=new TextField();
-
tf.setBounds(60,50,170,20);
-
-
Button b=new Button("click me");
-
b.setBounds(100,120,80,30);
-
-
Outer o=new Outer(this);
-
b.addActionListener(o);//passing outer class instance
-
-
add(b);add(tf);
-
-
setSize(300,300);
-
setLayout(null);
-
setVisible(true);
-
}
-
public static void main(String args[]){
-
new AEvent2();
-
}
-
}
-
import java.awt.event.*;
-
class Outer implements ActionListener{
-
AEvent2 obj;
-
Outer(AEvent2 obj){
-
this.obj=obj;
-
}
-
public void actionPerformed(ActionEvent e){
-
obj.tf.setText("welcome");
-
}
-
}
3) Example of event handling by Annonymous class:
-
import java.awt.*;
-
import java.awt.event.*;
-
class AEvent3 extends Frame{
-
TextField tf;
-
AEvent3(){
-
tf=new TextField();
-
tf.setBounds(60,50,170,20);
-
Button b=new Button("click me");
-
b.setBounds(50,120,80,30);
-
-
b.addActionListener(new ActionListener(){
-
public void actionPerformed(){
-
tf.setText("hello");
-
}
-
});
-
add(b);add(tf);
-
setSize(300,300);
-
setLayout(null);
-
setVisible(true);
-
}
-
public static void main(String args[]){
-
new AEvent3();
-
}
-
}
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.
Hierarchy of Java Swing classes
The hierarchy of java swing API is given below.
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
-
import javax.swing.*;
-
public class FirstSwingExample {
-
public static void main(String[] args) {
-
JFrame f=new JFrame();//creating instance of JFrame
-
-
JButton b=new JButton("click");//creating instance of JButton
-
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
-
-
f.add(b);//adding button in JFrame
-
-
f.setSize(400,500);//400 width and 500 height
-
f.setLayout(null);//using no layout managers
-
f.setVisible(true);//making the frame visible
-
}
-
}
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
-
import javax.swing.*;
-
public class Simple {
-
JFrame f;
-
Simple(){
-
f=new JFrame();//creating instance of JFrame
-
-
JButton b=new JButton("click");//creating instance of JButton
-
b.setBounds(130,100,100, 40);
-
-
f.add(b);//adding button in JFrame
-
-
f.setSize(400,500);//400 width and 500 height
-
f.setLayout(null);//using no layout managers
-
f.setVisible(true);//making the frame visible
-
}
-
-
public static void main(String[] args) {
-
new Simple();
-
}
-
}
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
-
import javax.swing.*;
-
public class Simple2 extends JFrame{//inheriting JFrame
-
JFrame f;
-
Simple2(){
-
JButton b=new JButton("click");//create button
-
b.setBounds(130,100,100, 40);
-
-
add(b);//adding button on frame
-
setSize(400,500);
-
setLayout(null);
-
setVisible(true);
-
}
-
public static void main(String[] args) {
-
new Simple2();
-
}}
BorderLayout (LayoutManagers):
LayoutManagers:
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface that is implemented by all the classes of layout managers. There are following classes that represents the layout managers:
-
java.awt.BorderLayout
-
java.awt.FlowLayout
-
java.awt.GridLayout
-
java.awt.CardLayout
-
java.awt.GridBagLayout
-
javax.swing.BoxLayout
-
javax.swing.GroupLayout
-
javax.swing.ScrollPaneLayout
-
javax.swing.SpringLayout etc.
BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each region (area) may contain one component only. It is the default layout of frame or window. The BorderLayout provides five constants for each region:
-
public static final int NORTH
-
public static final int SOUTH
-
public static final int EAST
-
public static final int WEST
-
public static final int CENTER
Constructors of BorderLayout class:
-
BorderLayout(): creates a border layout but with no gaps between the components.
-
JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps between the components.
Example of BorderLayout class:
-
import java.awt.*;
-
import javax.swing.*;
-
-
public class Border {
-
JFrame f;
-
Border(){
-
f=new JFrame();
-
-
JButton b1=new JButton("NORTH");;
-
JButton b2=new JButton("SOUTH");;
-
JButton b3=new JButton("EAST");;
-
JButton b4=new JButton("WEST");;
-
JButton b5=new JButton("CENTER");;
-
-
f.add(b1,BorderLayout.NORTH);
-
f.add(b2,BorderLayout.SOUTH);
-
f.add(b3,BorderLayout.EAST);
-
f.add(b4,BorderLayout.WEST);
-
f.add(b5,BorderLayout.CENTER);
-
-
f.setSize(300,300);
-
f.setVisible(true);
-
}
-
public static void main(String[] args) {
-
new Border();
-
}
-
}
GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each rectangle.
|
Constructors of GridLayout class:
-
GridLayout(): creates a grid layout with one column per component in a row.
-
GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps between the components.
-
GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and columns alongwith given horizontal and vertical gaps.
|
Example of GridLayout class:
-
import java.awt.*;
-
import javax.swing.*;
-
-
public class MyGridLayout{
-
JFrame f;
-
MyGridLayout(){
-
f=new JFrame();
-
-
JButton b1=new JButton("1");
-
JButton b2=new JButton("2");
-
JButton b3=new JButton("3");
-
JButton b4=new JButton("4");
-
JButton b5=new JButton("5");
-
JButton b6=new JButton("6");
-
JButton b7=new JButton("7");
-
JButton b8=new JButton("8");
-
JButton b9=new JButton("9");
-
-
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
-
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
-
-
f.setLayout(new GridLayout(3,3));
-
//setting grid layout of 3 rows and 3 columns
-
-
f.setSize(300,300);
-
f.setVisible(true);
-
}
-
public static void main(String[] args) {
-
new MyGridLayout();
-
}
-
}
FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default layout of applet or panel.
|
Fields of FlowLayout class:
-
public static final int LEFT
-
public static final int RIGHT
-
public static final int CENTER
-
public static final int LEADING
-
public static final int TRAILING
|
Constructors of FlowLayout class:
-
FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical gap.
-
FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal and vertical gap.
-
FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the given horizontal and vertical gap.
|
Example of FlowLayout class:
-
import java.awt.*;
-
import javax.swing.*;
-
-
public class MyFlowLayout{
-
JFrame f;
-
MyFlowLayout(){
-
f=new JFrame();
-
-
JButton b1=new JButton("1");
-
JButton b2=new JButton("2");
-
JButton b3=new JButton("3");
-
JButton b4=new JButton("4");
-
JButton b5=new JButton("5");
-
-
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
-
-
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
-
//setting flow layout of right alignment
-
-
f.setSize(300,300);
-
f.setVisible(true);
-
}
-
public static void main(String[] args) {
-
new MyFlowLayout();
-
}
-
}
BoxLayout class:
The BoxLayout is used to arrange the components either vertically or horizontally. For this purpose, BoxLayout provides four constants. They are as follows:
|
Note: BoxLayout class is found in javax.swing package.
Fields of BoxLayout class:
-
public static final int X_AXIS
-
public static final int Y_AXIS
-
public static final int LINE_AXIS
-
public static final int PAGE_AXIS
|
Constructor of BoxLayout class:
-
BoxLayout(Container c, int axis): creates a box layout that arranges the components with the given axis.
|
Example of BoxLayout class with Y-AXIS:
-
import java.awt.*;
-
import javax.swing.*;
-
-
public class BoxLayoutExample1 extends Frame {
-
Button buttons[];
-
-
public BoxLayoutExample1 () {
-
buttons = new Button [5];
-
-
for (int i = 0;i<5;i++) {
-
buttons[i] = new Button ("Button " + (i + 1));
-
add (buttons[i]);
-
}
-
-
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
-
setSize(400,400);
-
setVisible(true);
-
}
-
-
public static void main(String args[]){
-
BoxLayoutExample1 b=new BoxLayoutExample1();
-
}
-
}
Example of BoxLayout class with X-AXIS:
-
import java.awt.*;
-
import javax.swing.*;
-
-
public class BoxLayoutExample2 extends Frame {
-
Button buttons[];
-
-
public BoxLayoutExample2() {
-
buttons = new Button [5];
-
-
for (int i = 0;i<5;i++) {
-
buttons[i] = new Button ("Button " + (i + 1));
-
add (buttons[i]);
-
}
-
-
setLayout (new BoxLayout(this, BoxLayout.X_AXIS));
-
setSize(400,400);
-
setVisible(true);
-
}
-
-
public static void main(String args[]){
-
BoxLayoutExample2 b=new BoxLayoutExample2();
-
} }
CardLayout class
The CardLayout class manages the components in such a manner that only one component is visible at a time. It treats each component as a card that is why it is known as CardLayout.
|
Constructors of CardLayout class:
-
CardLayout(): creates a card layout with zero horizontal and vertical gap.
-
CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.
|
Commonly used methods of CardLayout class:
-
public void next(Container parent): is used to flip to the next card of the given container.
-
public void previous(Container parent): is used to flip to the previous card of the given container.
-
public void first(Container parent): is used to flip to the first card of the given container.
-
public void last(Container parent): is used to flip to the last card of the given container.
-
public void show(Container parent, String name): is used to flip to the specified card with the given name.
|
Example of CardLayout class:
-
import java.awt.*;
-
import java.awt.event.*;
-
-
import javax.swing.*;
-
-
public class CardLayoutExample extends JFrame implements ActionListener{
-
CardLayout card;
-
JButton b1,b2,b3;
-
Container c;
-
CardLayoutExample(){
-
-
c=getContentPane();
-
card=new CardLayout(40,30);
-
//create CardLayout object with 40 hor space and 30 ver space
-
c.setLayout(card);
-
-
b1=new JButton("Apple");
-
b2=new JButton("Boy");
-
b3=new JButton("Cat");
-
b1.addActionListener(this);
-
b2.addActionListener(this);
-
b3.addActionListener(this);
-
-
c.add("a",b1);c.add("b",b2);c.add("c",b3);
-
-
}
-
public void actionPerformed(ActionEvent e) {
-
card.next(c);
-
}
-
-
public static void main(String[] args) {
-
CardLayoutExample cl=new CardLayoutExample();
-
cl.setSize(400,400);
-
cl.setVisible(true);
-
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
-
}
-
}
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
-
It works at client side so less response time.
-
Secured
-
It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os etc.
Drawback of Applet
-
Plugin is required at client browser to execute applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the subclass of Component.
|
Lifecycle of Java Applet
-
Applet is initialized.
-
Applet is started.
-
Applet is painted.
-
Applet is stopped.
-
Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.
-
public void init(): is used to initialized the Applet. It is invoked only once.
-
public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
-
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
-
public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
-
public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used for drawing oval, rectangle, arc etc.
Who is responsible to manage the life cycle of an applet?
Java Plug-in software.
How to run an Applet?
There are two ways to run an applet
-
By html file.
-
By appletViewer tool (for testing purpose).
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that create an html file and place the applet code in html file. Now click the html file.
-
//First.java
-
import java.applet.Applet;
-
import java.awt.Graphics;
-
public class First extends Applet{
-
-
public void paint(Graphics g){
-
g.drawString("welcome",150,150);
-
}
-
-
}
Note: class must be public because its object is created by Java Plugin software that resides on the browser.
myapplet.html
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Dostları ilə paylaş: |