0% found this document useful (0 votes)
2 views

AWT Notes

AWT (Abstract Window Toolkit) is a Java API for creating graphical user interfaces (GUIs) that includes components like buttons and text fields, organized within containers such as Windows, Frames, and Panels. Event handling in AWT involves implementing listener interfaces to respond to user actions, with a focus on separating user interface logic from event processing. The document also provides examples of creating frames, handling events, and using various AWT components and listeners.

Uploaded by

sachintaba9
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

AWT Notes

AWT (Abstract Window Toolkit) is a Java API for creating graphical user interfaces (GUIs) that includes components like buttons and text fields, organized within containers such as Windows, Frames, and Panels. Event handling in AWT involves implementing listener interfaces to respond to user actions, with a focus on separating user interface logic from event processing. The document also provides examples of creating frames, handling events, and using various AWT components and listeners.

Uploaded by

sachintaba9
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

AWT

AWT stands for Abstract Window Toolkit. It is a platform dependent API for creating Graphical
User Interface (GUI) for java programs.
AWT hierarchy

COMPONENTS AND CONTAINERS


All the elements like buttons, text fields, scrollbars etc are known as components. To have everything
placed on a screen to a particular position, we have to add them to a container. A container is like a
screen wherein we are placing components like buttons, text fields, checkbox etc. In short, a container
contains and controls the layout of components. A container itself is a component.

There are four types of containers available in AWT: Window, Frame, Dialog and Panel.
Window: An instance of the Window class has no border and no title.
Dialog: Dialog class has border and title. An instance of the Dialog class cannot exist without an
associated instance of the Frame class.
Panel: Panel does not contain title bar, menu bar or border. It is a generic container for holding
components. An instance of the Panel class provides a container to which to add components.
1
Frame: A frame has title, border and menu bars. It can contain several components like buttons, text
fields, scrollbars etc.

We can create a GUI using Frame in two ways:


1) By extending Frame class
2) By creating the instance of Frame class

Example 1:
import java.awt.*;
public class SimpleExample extends Frame
{
SimpleExample()
{
Button b=new Button("Button!!");
b.setBounds(50,50,50,50); // setting button position on screen

add(b); //adding button into frame

setSize(500,300); //Setting Frame width and height

setTitle("This is my First AWT example"); //Setting the title of Frame

setLayout(new FlowLayout()); //Setting the layout for the Frame

/* By default frame is not visible so


* we are setting the visibility to true to make it visible.*/
setVisible(true);
}
public static void main(String args[])
{
SimpleExample fr=new SimpleExample(); // Creating the instance of Frame
}
}

Example 2:

import java.awt.*;
class First
{
First()
{
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[])
{
First f=new First();
}
}
2
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
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
 TextArea
o public void addTextListener(TextListener a){}
 Checkbox
o public void addItemListener(ItemListener a){}
 Choice
o public void addItemListener(ItemListener a){}
 List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Example 3:

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");
}

3
public static void main(String args[])
{
new AEvent();
}
}

HOW TO CLOSE WINDOW

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.

Example : Using Window Adapter in AWT to close the frame

import java.awt.*;
import java.awt.event.*; //For Event Handling
class Main_Thread extends WindowAdapter//This class for Window close method
{
Frame f;//create frame instance
Main_Thread()
{
f=new Frame();
f.addWindowListener(this); //Mendatory for Listener
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 void windowClosing(WindowEvent e) //This is method for Window Close Listener
{
f.dispose();
}

4
public static void main(String args[])
{
Main_Thread f=new Main_Thread();
}
}

Points to Remember:
1. While creating a frame (either by instantiating or extending Frame class), Following two
attributes are must for visibility of the frame:
o setSize(int width, int height);
o setVisible(true);
2. When you create other components like Buttons, TextFields, etc. Then you need to add it to the
frame by using the method - add(Component's Object);
3. You can add the following method also for resizing the frame - setResizable(true);
4. 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.

Program: Add component to Frame and close that frame.


import java.awt.*;
import java.awt.event.*;
public class First extends WindowAdapter
{
Frame f;//create frame instance
First()
{
f=new Frame();
Label firstName = new Label("First Name");
firstName.setBounds(20, 50, 80, 20);

Label lastName = new Label("Last Name");


lastName.setBounds(20, 80, 80, 20);

Label dob = new Label("Date of Birth");


dob.setBounds(20, 110, 80, 20);

TextField firstNameTF = new TextField();


firstNameTF.setBounds(120, 50, 100, 20);

TextField lastNameTF = new TextField();


lastNameTF.setBounds(120, 80, 100, 20);

TextField dobTF = new TextField();


dobTF.setBounds(120, 110, 100, 20);

Button sbmt = new Button("Submit");


5
sbmt.setBounds(20, 160, 100, 30);

Button reset = new Button("Reset");


reset.setBounds(120,160,100,30);

f.add(firstName);
f.add(lastName);
f.add(dob);
f.add(firstNameTF);
f.add(lastNameTF);
f.add(dobTF);
f.add(sbmt);
f.add(reset);

f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);

f.addWindowListener(this); //Mendatory for Listener


}
public void windowClosing(WindowEvent e) //This is method for Window Close Listener
{
//f.dispose();
System.exit(0);
}
public static void main(String[] args)
{
First awt = new First();
}
}
Output:

EVENT

6
What is an Event?

Change in the state of an object is known as event i.e. event describes the change in state of source.
Events are generated as result of user interaction with the graphical user interface components. For
example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an
item from list, scrolling the page are the activities that causes an event to happen.

Types of Events

The events can be broadly classified into two categories:

 Foreground Events - Those events which require the direct interaction of user. They are
generated as consequences of a person interacting with the graphical components in Graphical
User Interface. For example, clicking on a button, moving the mouse, entering a character
through keyboard, selecting an item from list, scrolling the page etc.
 Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer expires, an
operation completion are the example of background events.

What is Event Handling?

Event Handling is the mechanism that controls the event and decides what should happen if an event
occurs. This mechanism has the code which is known as event handler that is executed when an event
occurs. Java Uses the Delegation Event Model to handle the events. This model defines the standard
mechanism to generate and handle the events.

The Delegation Event Model has the following key participants namely:

 Source - The source is an object on which event occurs. Source is responsible for providing
information of the occurred event to it's handler. Java provide as with classes for source object.
 Listener - It is also known as event handler. Listener is responsible for generating response to
an event. From java implementation point of view the listener is also an object. Listener waits
until it receives an event. Once the event is received, the listeners process the event a then
returns.

The benefit of this approach is that the user interface logic is completely separated from the logic that
generates the event. The user interface element is able to delegate the processing of an event to the
separate piece of code. In this model, Listener needs to be registered with the source object so that the
listener can receive the event notification. This is an efficient way of handling the event because the
event notifications are sent only to those listeners that want to receive them.

Steps involved in event handling

 The User clicks the button and the event is generated.


 Now the object of concerned event class is created automatically and information about the
source and the event get populated with in same object.
 Event object is forwarded to the method of registered listener class.
 The method is now got executed and returns.

Points to remember about listener :In order to design a listener class we have to develop some
listener interfaces. These Listener interfaces forecast some public abstract callback methods which
must be implemented by the listener class.

 If you do not implement the any if the predefined interfaces then your class can not act as a
listener class for a source object.

7
Callback Methods

These are the methods that are provided by API provider and are defined by the application
programmer and invoked by the application developer. Here the callback methods represent an event
method. In response to an event java jre will fire callback method. All such callback methods are
provided in listener interfaces.

Event Listener
The Event listener represents the interfaces responsible to handle events. Java provides us various
Event listener classes. Every method of an event listener method has a single argument as an object
which is subclass of EventObject class. For example, mouse event listener methods will accept
instance of MouseEvent, where MouseEvent derives from EventObject.

AWT Event Listener Interfaces:

Following is the list of commonly used event listeners.

Sr. No. Control & Description


1 ActionListener
This interface is used for receiving the action events.
2 ItemListener
This interface is used for receiving the item events.
3 KeyListener
This interface is used for receiving the key events.
4 MouseListener
This interface is used for receiving the mouse events.
5 TextListener
This interface is used for receiving the text events.
6 WindowListener
This interface is used for receiving the window events.

AWT Adapters:

Adapters are abstract classes for receiving various events. The methods in these classes are empty.
These classes exist as convenience for creating listener objects.Following is the list of commonly used
adapters while listening GUI events in AWT.

Sr. Adapter & Description


No.
1 KeyAdapter
An abstract adapter class for receiving key events.
2 MouseAdapter
An abstract adapter class for receiving mouse events.
3 MouseMotionAdapter
An abstract adapter class for receiving mouse motion events.
4 WindowAdapter
An abstract adapter class for receiving window events.

8
Q1. Write a java program to create a frame containing three buttons (Yes, No, Close).
When button yes or no is pressed, the message "Button Yes/No is pressed" gets
displayed in label control. On pressing CLOSE button frame window gets closed.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class First extends JFrame
{
JButton yes, no, close;
JLabel lbl;
First()
{
yes = new JButton ("YES");
no = new JButton ("No");
close = new JButton ("CLOSE");
lbl = new JLabel ("");
setLayout (new FlowLayout());

/*setLayout(new BorderLayout());
add("North", new TextField("Title",50));*/

setSize (400, 200);


add (yes);

add (no);
add (close);
add (lbl);
setVisible (true);

//setDefaultCloseOperation(JFrame.EXIT_NO_CLOSE);
ButtonHandler bh = new ButtonHandler ();
yes.addActionListener (bh);
yes.addActionListener (bh);
no.addActionListener (bh);
close.addActionListener (bh);
}
class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent ae)
{
if (ae.getSource () == yes)
{
lbl.setText ("Button Yes is pressed");
}
if (ae.getSource () == no)
{

9
lbl.setText ("Button No is pressed");
}
if (ae.getSource () == close)
{
System.exit (0);
}
}
}
public static void main (String args[])
{
First f= new First ();
}
}

Q2. Write a Java program to create a combo box which includes list of
subjects. Display the selected subject in the text field using Swing.
Answer: In this example a combo box having the list of subjects. When any one of
the records selected from the combo box, it will display on the text field.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;

class Combo_List extends JFrame


{
JFrame frame = new JFrame(" ");
JComboBox cb1, cb2;
JTextField txtsub;
JLabel lblsub, sub;

public Combo_List ()
{
super(" COMBO LIST");
txtsub = new JTextField();
10
cb1 = new JComboBox();
lblsub = new JLabel(" SELECT SUBJECT:");
sub= new JLabel(" SUBJECT NAME:");

add(lblsub);
add(cb1);
add(txtsub);
add(sub);
setSize(500,300);
setLocation(0,0);
setResizable(false);
setLayout(null);

setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
lblsub.setBounds(50,50,250,40);
cb1.setBounds(170,50,250,35);
sub.setBounds(50,150,250,40);
txtsub.setBounds(170,150,250,35);

cb1.addItem("DATA STRUCTURE IN C");


cb1.addItem("OBJECT ORIENTED IN C++");
cb1.addItem("CORE JAVA");
cb1.addItem("ADVANCE JAVA");
cb1.addItem("DATABASE MANAGEMENT SYSTEM");
cb1.addItem("ADVANCE DATABASE MANAGEMENT SYSTEM");
cb1.addItem("OPERATING SYSTEM");
cb1.addItem("NETWORKING");
cb1.addItem("ANDROID");

cb1.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent event)
{
if (event.getStateChange() == ItemEvent.SELECTED)
{
try
{
String no=cb1.getSelectedItem().toString();
txtsub.setText(no);
}
catch (Exception ex)
{
System.out.println("An error Occured");
}
}
}
});

11
}
public static void main(String[] args)
{
new Combo_List ();
}
}
Q3. Write a java program using swing to create a frame having three text fields. Accept number
in first textfield and display previous number in second textfield and next number in the third
textfield.
Answer:
Below example shows how to find previous and next number in different textboxes using java Swing.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class First extends JFrame implements ActionListener
{
JLabel textLabel, Label1, Label2;
JTextField Text1, Text2, Text3;
JButton ok, exit;
JPanel pan1, pan2;
int occurrences = 0, i = 0;
public First()
{
textLabel = new JLabel("Enter Number ",JLabel.CENTER);
Label1 = new JLabel("Previous Number ",JLabel.CENTER);
Label2 = new JLabel("Next Number ",JLabel.CENTER);
Text1 = new JTextField(20);
Text2 = new JTextField(20);
Text3 = new JTextField(20);
setLayout(new FlowLayout());
/*pan1 = new JPanel();
pan1.setLayout(new GridLayout(4,2));
pan1.add(textLabel);
pan1.add(Text1);
pan1.add(Label1);
pan1.add(Text2);
pan1.add(Label2);
pan1.add(Text3);*/

add(textLabel);
add(Text1);
add(Label1);
add(Text2);
add(Label2);
add(Text3);

ok = new JButton("ok");
exit = new JButton("Exit");
12
ok.addActionListener(this);
exit.addActionListener(this);

/* pan2 = new JPanel();


pan2.setLayout(new FlowLayout());
pan2.add(ok);
pan2.add(exit);
add(pan1,"Center");
add(pan2,"South");*/
add(ok);
add(exit);
setTitle("Number Operation");
setSize(400, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
JButton btn = (JButton)ae.getSource();
if (btn == ok)
{
String f = Text1.getText();
int s=Integer.parseInt(f);
s=s+1;
Text3.setText(Integer.toString(s));
int a=Integer.parseInt(f);
a=a-1;
Text2.setText(Integer.toString(a));
}
if (btn == exit)
{
System.exit(0);
}
}
public static void main(String[] args)
{
new First();
}
}

Example 4. Calculator

13
import java.awt.*;
import java.awt.event.*;

class First implements ActionListener


{
//Declaring Objects
Frame f=new Frame();
Label l1=new Label("First Number");
Label l2=new Label("Second Number");
Label l3=new Label("Result");
TextField t1=new TextField();
TextField t2=new TextField();
TextField t3=new TextField();
Button b1=new Button("Add");
Button b2=new Button("Sub");
Button b3=new Button("Mul");
Button b4=new Button("Div");
Button b5=new Button("Cancel");
First()
{
//Giving Coordinates
l1.setBounds(50,100,100,20);
l2.setBounds(50,140,100,20);
l3.setBounds(50,180,100,20);
t1.setBounds(200,100,100,20);
t2.setBounds(200,140,100,20);
t3.setBounds(200,180,100,20);
b1.setBounds(50,250,50,20);
b2.setBounds(110,250,50,20);
b3.setBounds(170,250,50,20);
b4.setBounds(230,250,50,20);
b5.setBounds(290,250,50,20);

//Adding components to the frame


f.add(l1);
f.add(l2);
f.add(l3);
f.add(t1);
f.add(t2);
f.add(t3);
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);

b1.addActionListener(this);

14
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);

f.setLayout(null);
f.setVisible(true);
f.setSize(400,350);
}
public void actionPerformed(ActionEvent e)
{
int n1=Integer.parseInt(t1.getText());
int n2=Integer.parseInt(t2.getText());
if(e.getSource()==b1)
{
t3.setText(String.valueOf(n1+n2));
}
if(e.getSource()==b2)
{
t3.setText(String.valueOf(n1-n2));
}
if(e.getSource()==b3)
{
t3.setText(String.valueOf(n1*n2));
}
if(e.getSource()==b4)
{
t3.setText(String.valueOf(n1/n2));
}
if(e.getSource()==b5)
{
System.exit(0);
}
}
public static void main(String...s)
{
new First();
}
}

15
Example 5: Java program to store a Student Information in a File using
AWT.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class First{

// Function to write a student information


public static void StudentInfo()
{
JFrame f = new JFrame("Student Details Form");

// Creating the labels


JLabel l1, l2, l3, l4, l5;

// Creating three text fields.


// One for student name, one for college mail ID and one
// for Mobile No
JTextField t1, t2, t3;

// Creating two JComboboxes one for Branch and one for Section
JComboBox j1, j2;

JButton b1, b2;

// Naming the labels and setting the bounds for the labels
l1 = new JLabel("Student Name:");
l1.setBounds(50, 50, 100, 30);
l2 = new JLabel("College Email ID:");
l2.setBounds(50, 120, 120, 30);
l3 = new JLabel("Branch:");
l3.setBounds(50, 190, 50, 30);
l4 = new JLabel("Section:");
l4.setBounds(420, 50, 70, 30);
l5 = new JLabel("Mobile No:");
l5.setBounds(420, 120, 70, 30);

// Creating the textfields and


// setting the bounds for textfields
t1 = new JTextField();
t1.setBounds(150, 50, 130, 30);
t2 = new JTextField();
t2.setBounds(160, 120, 130, 30);
t3 = new JTextField();
t3.setBounds(490, 120, 130, 30);

// Creating two string arrays one for


// braches and other for sections
String s1[]= { " ", "CSE", "ECE", "EEE","CIVIL", "MEC", "Others" };
String s2[]= { " ", "Section-A", "Section-B", "Section-C", "Section-D"};

// Creating two JComboBoxes one for selecting branch and other for

16
// selecting the sectionand setting the bounds
j1 = new JComboBox(s1);
j1.setBounds(120, 190, 100, 30);
j2 = new JComboBox(s2);
j2.setBounds(470, 50, 140, 30);

// Creating one button for Saving and other button to close and setting the bounds
b1 = new JButton("Save");
b1.setBounds(150, 300, 70, 30);
b2 = new JButton("close");
b2.setBounds(420, 300, 70, 30);

// Adding action listener


b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// Getting the text from text fields and JComboboxes
// and copying it to a strings

String s1 = t1.getText();
String s2 = t2.getText();
String s3 = j1.getSelectedItem() + "";
String s4 = j2.getSelectedItem() + "";
String s5 = t3.getText();
if (e.getSource() == b1) {
try {

// Creating a file and writing the data into a Textfile.


FileWriter w= new FileWriter("GFG.txt", true);
w.write(s1 + "\n");
w.write(s2 + "\n");
w.write(s3 + "\n");
w.write(s4 + "\n");
w.write(s5 + "\n");
w.close();
}
catch (Exception ae) {
System.out.println("Data Base Error Occured");
}
}

// Shows a Pop up Message when save button is clicked


JOptionPane.showMessageDialog(f,"Successfully Saved"+ " The Details");
}
});

// Action listener to close the form


b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
f.dispose();
}
});

// Default method for closing the frame

17
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});

// Adding the created objects


// to the frame
f.add(l1);
f.add(t1);
f.add(l2);
f.add(t2);
f.add(l3);
f.add(j1);
f.add(l4);
f.add(j2);
f.add(l5);
f.add(t3);
f.add(b1);
f.add(b2);
f.setLayout(null);
f.setSize(700, 600);
f.setVisible(true);
}
// Driver code
public static void main(String args[])
{
StudentInfo();
}
}

18
AWT Button
In Java, AWT contains a Button Class. It is used for creating a labelled button which can perform an
action.
AWT Button Classs Declaration:
public class Button extends Component implements Accessible

Example:
Lets take an example to create a button and it to the frame by providing coordinates.

import java.awt.*;
public class ButtonDemo1
{
public static void main(String[] args)
{
Frame f1=new Frame("Button Demo");
Button b1=new Button("Press Here");
b1.setBounds(80,200,80,50);
f1.add(b1);
f1.setSize(500,500);
f1.setLayout(null);
f1.setVisible(true);
}
}
AWT Label
In Java, AWT contains a Label Class. It is used for placing text in a container. Only Single line text is
allowed and the text can not be changed directly.
Label Declaration:
public class Label extends Component implements Accessible
Example:
In this example, we are creating two labels to display text to the frame.

import java.awt.*;
class LabelDemo1
{
public static void main(String args[])
{
Frame l_Frame= new Frame("Label Demo");
Label lab1;
lab1=new Label("Welcome to IIMT");
lab1.setBounds(50,50,200,30);
l_Frame.add(lab1); l_Frame.setSize(500,500);
l_Frame.setLayout(null);
l_Frame.setVisible(true);
}
}

19
AWT TextField
In Java, AWT contains aTextField Class. It is used for displaying single line text.
TextField Declaration:
public class TextField extends TextComponent
Example:
We are creating two textfields to display single line text string. This text is editable in nature, see the
below example.

import java.awt.*;
class TextFieldDemo1
{
public static void main(String args[])
{
Frame TextF_f= new Frame("studytonight ==>TextField");
TextField text1,text2;
text1=new TextField("Welcome to studytonight");
text1.setBounds(60,100, 230,40);
text2=new TextField("This tutorial is of Java");
text2.setBounds(60,150, 230,40);
TextF_f.add(text1);
TextF_f.add(text2);
TextF_f.setSize(500,500);
TextF_f.setLayout(null);
TextF_f.setVisible(true);
}
}
AWT TextArea
In Java, AWT contains a TextArea Class. It is used for displaying multiple-line text.
TextArea Declaration:
public class TextArea extends TextComponent
Example:
In this example, we are creating a TextArea that is used to display multiple-line text string and allows
text editing as well.

import java.awt.*;
public class TextAreaDemo1
{
TextAreaDemo1()
{
Frame textArea_f= new Frame();
TextArea area=new TextArea("Welcome to studytonight.com");
area.setBounds(30,40, 200,200);
textArea_f.add(area);
textArea_f.setSize(300,300);
textArea_f.setLayout(null);

20
textArea_f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaDemo1();
}
}

AWT Checkbox
In Java, AWT contains a Checkbox Class. It is used when we want to select only one option i.e true or
false. When the checkbox is checked then its state is "on" (true) else it is "off"(false).

Checkbox Syntax
public class Checkbox extends Component implements ItemSelectable, Accessible

Example:
In this example, we are creating checkbox that are used to get user input. If checkbox is checked it
returns true else returns false.

import java.awt.*;
public class CheckboxDemo1
{
CheckboxDemo1()
{
Frame checkB_f= new Frame("studytonight ==>Checkbox Example");
Checkbox ckbox1 = new Checkbox("Yes", true);
ckbox1.setBounds(100,100, 60,60);
Checkbox ckbox2 = new Checkbox("No");
ckbox2.setBounds(100,150, 60,60);
checkB_f.add(ckbox1);
checkB_f.add(ckbox2);
checkB_f.setSize(400,400);
checkB_f.setLayout(null);
checkB_f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxDemo1();
}
}

21
AWT CheckboxGroup
In Java, AWT contains aCheckboxGroup Class. It is used to group a set of Checkbox. When
Checkboxes are grouped then only one box can be checked at a time.

CheckboxGroup Declaration:
public class CheckboxGroup extends Object implements Serializable

Example:
This example creates a checkboxgroup that is used to group multiple checkbox in a single unit. It is
helpful when we have to select single choice among the multiples.

import java.awt.*;
public class CheckboxGroupDemo
{
CheckboxGroupDemo()
{
Frame ck_groupf= new Frame("studytonight ==>CheckboxGroup");
CheckboxGroupobj = new CheckboxGroup();
Checkbox ckBox1 = new Checkbox("Yes", obj, true);
ckBox1.setBounds(100,100, 50,50);
Checkbox ckBox2 = new Checkbox("No", obj, false);
ckBox2.setBounds(100,150, 50,50);
ck_groupf.add(ckBox1);
ck_groupf.add(ckBox2);
ck_groupf.setSize(400,400);
ck_groupf.setLayout(null);
ck_groupf.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupDemo();
}
}

22
AWT Choice
In Java, AWT contains a Choice Class. It is used for creating a drop-down menu of choices. When a
user selects a particular item from the drop-down then it is shown on the top of the menu.

Choice Declaration:
public class Choice extends Component implements ItemSelectable, Accessible

Example:
In this example, we are creating drop-down menu that is used to get user choice from multiple
choices.

import java.awt.*;
public class ChoiceDemo
{
ChoiceDemo()
{
Frame choice_f= new Frame();
Choice obj=new Choice();
obj.setBounds(80,80, 100,100);
obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
choice_f.add(obj);
choice_f.setSize(400,400);
choice_f.setLayout(null);
choice_f.setVisible(true);
}
public static void main(String args[])
{
new ChoiceDemo();
}
}

23
AWT List
In Java, AWT contains a List Class. It is used to represent a list of items together. One or more than
one item can be selected from the list.

List Declaration:
public class List extends Component implements ItemSelectable, Accessible

Example:
In this example, we are creating a list that is used to list out the items.

import java.awt.*;
public class ListDemo
{
ListDemo()
{
Frame list_f= new Frame();
List obj=new List(6);
obj.setBounds(80,80, 100,100);
obj.add("Red");
obj.add("Blue");
obj.add("Black");
obj.add("Pink");
obj.add("White");
obj.add("Green");
list_f.add(obj);
list_f.setSize(400,400);
list_f.setLayout(null);
list_f.setVisible(true);
}
public static void main(String args[])
{
new ListDemo();
}
}

24
AWT Canvas
In Java, AWT contains a Canvas Class. A blank rectangular area is provided. It is used when a user
wants to draw on the screen.
Declaration:
public class Canvas extends Component implements Accessible
Example:
The canvas is used to provide a place to draw using mouse pointer. We can used it to get user
architectural user input.

import java.awt.*;
public class CanvasDemo1
{
public CanvasDemo1()
{
Frame canvas_f= new Frame("studytonight ==> Canvas");
canvas_f.add(new CanvasDemo());
canvas_f.setLayout(null);
canvas_f.setSize(500, 500);
canvas_f.setVisible(true);
}
public static void main(String args[])
{
new CanvasDemo1();
}
}
class CanvasDemo extends Canvas
{
public CanvasDemo() {
setBackground (Color.WHITE);
setSize(300, 200);
}
public void paint(Graphics g)
{
g.setColor(Color.green);
g.fillOval(80, 80, 150, 75);
}
}

MOVING BALL
25
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class cANVASeXAMPLE extends JPanel


{
int x = 0;
int y = 0;

private void moveBall() {


x = x + 1;
y = y + 1;
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(x, y, 30, 30);
}

public static void main(String[] args) throws InterruptedException {


JFrame frame = new JFrame("Mini Tennis");
cANVASeXAMPLE game = new cANVASeXAMPLE();
frame.add(game);
frame.setSize(300, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

while (true) {
game.moveBall();
game.repaint();
Thread.sleep(10);
}
}
}

Output: C:\Users\varun kumar gupta\OneDrive\Desktop\animation.gif

Analyzing our paint method


As we said in the last tutorial, this method is run each time the operative system tells
the AWT engine that it is necessary to paint the canvas. If we run the repaint() method
of a JPanel object, what we are doing is telling the AWT engine to execute the paint
method as soon as possible. Calling repaint(), the canvas is painted again and we can
see the changes in the position of the circle.

26
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(x, y, 30, 30);
}
The call to "super.paint(g)", cleans the screen and if we comment this line we can see
the following effect:

The instruction; "g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,


RenderingHints.VALUE_ANTIALIAS_ON)" makes the borders of the figures smoother,
as you can see in the following graphic. The circle on the left is without applying
ANTIALIAS and the one on the right; applying ANTIALIAS.

Analyzing the concurrence and the behaviour of the threads.


At the beginning of the execution of the main method, there is only one thread. We can
see this, putting a breakpoint in the first line of the main method.

MENU

27
As we know that every top-level window has a menu bar associated with it. This menu bar consists of
various menu choices available to the end user. Further each choice contains list of options which is
called drop down menus. Menu and MenuItem controls are subclass of Menu Component class.

Menu Hierarchy

Menu Controls
Sr. Control & Description
No.
1 MenuComponent
It is the top level class for all menu related controls.
2 MenuBar
The MenuBar object is associated with the top-level window.
3 MenuItem
The items in the menu must belong to the MenuItem or any of its subclass.
4 Menu
The Menu object is a pull-down menu component which is displayed from the menu bar.
5 CheckboxMenuItem
CheckboxMenuItem is subclass of MenuItem.
6 PopupMenu
PopupMenu can be dynamically popped up at a specified position within a component.

28
Menu Program Using Cut Copy Paste(CCP) Example:

import javax.swing.*;
import java.awt.event.*;
public class Menu_Example implements ActionListener
{
JFrame f;
JMenuBar mb;
JMenu file,edit,help;
JMenuItem cut,copy,paste,selectAll;
JTextArea ta;
Menu_Example(){
f=new JFrame();
cut=new JMenuItem("cut");
copy=new JMenuItem("copy");
paste=new JMenuItem("paste");
selectAll=new JMenuItem("selectAll");
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
selectAll.addActionListener(this);
mb=new JMenuBar();
file=new JMenu("File");
edit=new JMenu("Edit");
help=new JMenu("Help");
edit.add(cut); edit.add(copy); edit.add(paste); edit.add(selectAll);
mb.add(file); mb.add(edit); mb.add(help);
ta=new JTextArea();
ta.setBounds(5,5,360,320);
f.add(mb);f.add(ta);
f.setJMenuBar(mb);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
I f(e.getSource()==cut)
ta.cut();
29
if(e.getSource()==paste)
ta.paste();
if(e.getSource()==copy)
ta.copy();
if(e.getSource()==selectAll)
ta.selectAll();
}
public static void main(String[] args)
{
new Menu_Example();
}
}

LAYOUT

Layout means the arrangement of components within the container. In other way we can say that
placing the components at a particular position within the container. The task of layouting the controls
are done automatically by the Layout Manager.

Layout Manager

The layout manager automatically positions all the components within the container. If we do not use
layout manager then also the components are positioned by the default layout manager. It is possible
to layout the controls by hand but it becomes very difficult because of the following two reasons.

 It is very tedious to handle a large number of controls within the container.


 Oftenly, the width and height information of a component is not given when we need to
arrange them.

Java provides us with various layout managers to position the controls. The properties like size shape
and arrangement varies from one layout manager to other layout manager. When the size of the applet
or the application window changes the size, shape and arrangement of the components also changes in
response i.e. the layout managers adapt to the dimensions of appletviewer or the application window.

The layout manager is associated with every Container object. Each layout manager is an object of the
class that implements the LayoutManager interface.

Following are the interfaces defining functionalities of Layout Managers.

AWT Layout Manager Classes:

Following is the list of commonly used controls while designed GUI using AWT.

Sr. LayoutManager & Description


No.
1 BorderLayout
The borderlayout arranges the components to fit in the five regions: east, west, north, south
and center.

30
2 CardLayout
The CardLayout object treats each component in the container as a card. Only one card is
visible at a time.
3 FlowLayout
The FlowLayout is the default layout. It layouts the components in a directional flow.
4 GridLayout
The GridLayout manages the components in form of a rectangular grid.
5 GridBagLayout
This is the most flexible layout manager class. The object of GridBagLayout aligns the
component vertically, horizontally or along their baseline without requiring the components
of same size.

The FlowLayout Class

The FlowLayout class is the most basic of layouts. Using the flow layout, components are added to the
panel one at a time, row by row. If a component doesn’t fit onto a row, it’s wrapped onto the next row.
The flow layout also has an alignment, which determines the alignment of each row. By default, each
row is aligned centered.

Border Layouts

Border layouts behave differently from flow and grid layouts. When you add a component to a panel
that uses a border layout, you indicate its placement as a geographic direction: north, south, east, west,
and center. The components around all the edges are laid out with as much size as they need; the
component in the center, if any, gets any space left over.

31
To use a border layout, you create it as you do the other layouts:
setLayout(new BorderLayout());

Then you add the individual components by using a special add() method:
The first argument to add() is a string indicating the position of the component within the layout:
add(“North”, new TextField(“Title”,50));
add(“South”, new TextField(“Status”,50));

Border layouts can also have horizontal and vertical gaps. Note that the north and south components
extend all the way to the edge of the panel, so the gap will result in less space for the east, right, and
center components. To add gaps to a border layout, include those pixel values as before:

setLayout(new BorderLayout(10,10));

Card Layouts

Card layouts are different from the other layouts. Unlike with the other three layouts, when you add
components to a card layout, they are not all displayed on the screen at once. Card layouts are used to
produce slide shows of components, one at a time.
Generally when you create a card layout, the components you add to it will be other container
components usually panels. You can then use different layouts for those individual “cards” so that
each screen has its own look.
When you add each “card” to the panel, you can give it a name. Then you can use methods defined on
the CardLayout class to move back and forth between different cards in the layout.

For example, here’s how to create a card layout containing three cards:
setLayout(new CardLayout());
Panel one = new Panel()
add(“first”, one);
Panel two = new Panel()
add(“second”, two);
Panel three = new Panel()
add(“third”, three);
show(this, “second”);

32
INSETS
Whereas horizontal gap and vertical gap are used to determine the amount of space between
components in a panel, insets are used to determine the amount of space around the panel itself. The
insets class provides values for the top, bottom, left, and right insets, which are then used when the
panel itself is drawn.
Ex: shows an inset in a GridLayout.

To include an inset, override the insets() method in your class (your Applet class or other class that
serves as a panel):
public Insets insets()
{
return new Insets(10,10,10,10);
}

The arguments to the Insets constructor provide pixel insets for the top, bottom, left, and right edges of
the panel. This particular example provides an inset of 10 pixels on all four sides of the panel.

GRID LAYOUT

33
34

You might also like