Java Unit4
Java Unit4
Event Handling
In general we can not perform any operation on dummy GUI screen even any
button click or select any item.
To perform some operation on these dummy GUI screen you need some
predefined classes and interfaces.
All these type of classes and interfaces are available in java.awt.event package.
Changing the state of an object is known as an event.
The process of handling the request in GUI screen is known as event handling
(event represent an action). It will be changes component to component.
Note: In event handling mechanism event represent an action class and Listener
represent an interface. Listener interface always contains abstract methods so here
you need to write your own logic.
Events
The Events are the objects that define state change in a source. An event can be
generated as a reaction of a user while interacting with GUI elements.
Some of the event generation activities are moving the mouse pointer, clicking on a
button, pressing the keyboard key, selecting an item from the list, and so on. We
can also consider many other user operations as events.
Event Sources
A source is an object that causes and generates an event. It generates an event
when the internal state of the object is changed. The sources are allowed to
generate several different types of events.
A source must register a listener to receive notifications for a specific event. Each
event contains its registration method. Below is an example:
Example
public void addTypeListener (TypeListener e1)
From the above syntax, the Type is the name of the event, and e1 is a
reference to the event listener.
For example, for a keyboard event listener, the method will be called as
addKeyListener().
For the mouse event listener, the method will be called as
addMouseMotionListener().
When an event is triggered using the respected source, all the events will be
notified to registered listeners and receive the event object.
This process is known as event multicasting.
Event Listeners
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 listener
process the event and then returns.
Event classes and Listener interfaces
Registration Methods
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)
{
}
For handling event for mouse you need MouseEvent class and 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.
Example
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener
{
Label l;
MouseListenerExample()
{
addMouseListener(this);
l=new Label();
add(l);
setSize(300,300);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e)
{
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
{
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e)
{
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{
l.setText("Mouse Released");
}
public static void main(String[] args)
{
new MouseListenerExample();
}
}
Output:
Example
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements KeyListener
{
Label l;
TextArea area;
KeyListenerExample()
{
l=new Label();
l.setBounds(20,50,100,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
area.addKeyListener(this);
add(l);
add(area);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e)
{
l.setText("Key Pressed");
}
public void keyReleased(KeyEvent e)
{
l.setText("Key Released");
}
public void keyTyped(KeyEvent e)
{
l.setText("Key Typed");
}
public static void main(String[] args)
{
new KeyListenerExample();
}
}
Output:
Adapter Classes
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapte HierarchyBoundsListener
r
import java.awt.*;
import java.awt.event.*;
public class AdapterExample
{
Frame f;
AdapterExample()
{
f=new Frame("Window Adapter");
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
f.dispose();
}
});
f.setSize(400,400);
f.setVisible(true);
}
public static void main(String[] args)
{
new AdapterExample();
}
}
AWT
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface
(GUI) or windows-based applications in Java.
The java.awt package provides classes for AWT API such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
• Layout Managers: Layout Managers are responsible for arranging data in the
containers sone of the layout managers are BorderLayout, FlowLayout, etc.
The hierarchy of Java AWT classes are given below.
• Event Handling: AWT allows the user to handle the events like mouse clicks,
dialog box. The Window class extends the Container class, which means it can
contain other components, such as buttons, labels, and text fields.
2.Panel: Panel is a container class in Java. It is a lightweight container that can
user input.
Components
All the elements like the button, text fields, scroll bars, etc. are called components.
In Java AWT, there are classes for each component as shown in above diagram. In
order to place every component in a particular position on a screen, we need to add
them to a container.
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.
It is basically a screen where the where the components are placed at their specific
locations. Thus it contains and controls the layout of components.
Note: A container itself is a component (see the above diagram), therefore we can
add a container inside container.
Types of containers:
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. We need to create an
instance of Window class to create this container.
Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is
generic container for holding the components. It can have other components like
button, text field etc. An instance of Panel class creates a container, in which we
can add components.
Frame
The Frame is the container that contain title bar and border and can have menu
bars. It can have other components like button, text field, scrollbar etc. Frame is
most widely used container while developing an AWT application.
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.
Let's see a simple example of AWT where we are inheriting Frame class. Here, we
are showing Button component on the Frame.
import java.awt.*;
// extending Frame class to our class AWTExample1
public class AWTExample1 extends Frame {
AWTExample1() {
Button b = new Button("Click Me!!"); // creating a button
b.setBounds(30,100,80,30); // setting button position on screen
add(b); // adding button into frame
setSize(300,300); // frame size 300 width and 300 height
setTitle("This is our basic AWT example"); // setting the title of Frame
setLayout(null); // no layout manager
setVisible(true); // now frame will be visible, by default it is not visible
}
public static void main(String args[]) {
// creating instance of Frame class
AWTExample1 f = new AWTExample1();
}
}
The setBounds(int x-axis, int y-axis, int width, int height) method is used in the
above example that sets the position of the awt button.
Output:
AWT Example by Association
Let's see a simple example of AWT where we are creating instance of Frame class.
Here, we are creating a TextField, Label and Button component on the Frame.
import java.awt.*;
// class AWTExample2 directly creates instance of Frame class
class AWTExample2 {
// initializing using constructor
AWTExample2() {
Frame f = new Frame(); // creating a Frame
Label l = new Label("Employee id:"); // creating a Label
Button b = new Button("Submit"); // creating a Button
TextField t = new TextField(); // creating a TextField
// setting position of above components in the frame
l.setBounds(20, 80, 80, 30);
t.setBounds(20, 100, 80, 30);
b.setBounds(100, 100, 80, 30);
f.add(b); // adding components into frame
f.add(l);
f.add(t);
// frame size 300 width and 300 height
f.setSize(400,300);
f.setTitle("Employee info"); // setting the title of frame
f.setLayout(null);
f.setVisible(true); // setting visibility of frame
}
public static void main(String args[]) {
// creating instance of Frame class
AWTExample2 awt_obj = new AWTExample2();
} }
Output:
Java AWT Label
The object of the 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 a
programmer but a user cannot edit it directly.
It is called a passive control as it does not create any event when it is accessed. To
create a label, we need to create the object of Label class.
1.static int LEFT: It specifies that the label should be left justified.
2.static int RIGHT: It specifies that the label should be right justified.
3.static int CENTER: It specifies that the label should be placed in center.
2. Label(String text) It constructs a label with the given string (left justified by default).
Label(String text, int It constructs a label with the specified string and the specified
3.
alignement) alignment.
7. protected String paramString() It returns the string the state of the label.
Method inherited
•java.awt.Component
•java.lang.Object
In the following example, we are creating two labels l1 and l2 using the
Label(String text) constructor and adding them into the frame.
import java.awt.*;
public class LabelExample {
public static void main(String args[]){
// creating the object of Frame class and Label class
Frame f = new Frame ("Label example");
Label l1, l2;
// initializing the labels
l1 = new Label ("First Label.");
l2 = new Label ("Second Label.");
// set the location of label
l1.setBounds(50, 100, 100, 30);
l2.setBounds(50, 150, 100, 30);
// adding labels to the frame
f.add(l1);
f.add(l2);
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
Button in Java AWT
The ‘Button’ class is a part of the ‘java.awt’ package which has a collection of
classes and methods for creating GUI components. Java AWT Buttons can be used to
perform several actions like saving a file, closing a window, submitting a form, or
triggering any specific action.
When we press a button, AWT creates an instance of ActionEvent and delivers it by
calling processEvent on the button. The processEvent method of the button accepts
all events and then sends an action event to its own function processActionEvent.
The ActionListener interface must be implemented if one wants to execute an action
when a button is pressed.
Syntax of Java AWT Button
public class Button extends Component implements Accessible
Constructors of Button
There are 2 types of Constructors in the AWT Button class.
Button(): Creates a new button with the label as an empty string.
•Button(String label): Creates a new button with the label as the specified string
as a parameter.
void removeActionListener(ActionListener l) The specified action listener is removed from the button.
void setLabel(String label) Sets the button’s label to be the specified string.
import java.awt.Button;
import java.awt.Frame;
// Create a button
frame.setSize(400, 300);
frame.setLayout(null);
output:
Button Example(ActionListener):
In this example, an ActionListener is called when the button is clicked. It
triggers an event and the label is displayed on the screen.
import java.awt.*;
import java.awt.event.*;
// Create a label
Label label = new Label();
frame.add(label);
frame.setBackground(Color.LIGHT_GRAY);
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
}
}
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
• public class Canvas extends Component implements Accessible
import java.awt.*;
public class CanvasExample{
public CanvasExample(){
Frame f= new Frame("Canvas Example");
f.add(new MyCanvas());
f.setLayout(null);
f.setSize(400, 400);
f.setVisible(true);
}
public static void main(String args[]){
new CanvasExample();
} }
class MyCanvas extends Canvas{
public MyCanvas() {
setBackground (Color.GRAY);
setSize(300, 200);
}
public void paint(Graphics g){
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
} }
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.
It can be added to top-level container like Frame or a component like Panel. The
Scrollbar class extends the Component class.
Sr.
Constructor Description
no.
1 Scrollbar() Constructs a new vertical scroll bar.
Scrollbar(int orientation, int Constructs a new scroll bar with the specified
3 value, int visible, int orientation, initial value, visible amount, and
•Value: specify the starting position of the knob of Scrollbar on its track.
Example :
s.addAdjustmentListener(new AdjustmentListener() {
import java.awt.*;
public class ScrollbarExample1 {
ScrollbarExample1() {
Frame f = new Frame("Scrollbar Example");
Scrollbar s = new Scrollbar();
s.setBounds (100, 100, 50, 100);
f.add(s);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]) {
new ScrollbarExample1();
}
}
output:
Java AWT TextField
The object of a TextField class is a text component that allows a user to enter a
single line text and edit it. It inherits TextComponent class, which further inherits
Component class.
When we enter a key in the text field (like key pressed, key released or key typed),
the event is sent to TextField. Then the KeyEvent is passed to the registered
KeyListener. It can also be done using ActionEvent; if the ActionEvent is enabled on
the text field, then the ActionEvent may be fired by pressing return key. The event
is handled by the ActionListener interface.
Sr.
Constructor Description
no.
1. TextField() It constructs a new text field component.
TextField(String text, int It constructs a new text field with the given text and given
4.
columns) number of columns (width).
import java.awt.*;
public class TextFieldExample1 {
public static void main(String args[]) {
Frame f = new Frame("TextField Example");
TextField t1, t2;
t1 = new TextField("Welcome to Javatpoint.");
t1.setBounds(50, 100, 200, 30);
t2 = new TextField("AWT Tutorial");
t2.setBounds(50, 150, 200, 30);
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
Java AWT TextField Example with ActionListener
import java.awt.*;
import java.awt.event.*;
public class TextFieldExample2 extends Frame implements ActionListener {
TextField tf1, tf2, tf3;
Button b1, b2;
TextFieldExample2() {
tf1 = new TextField();
tf1.setBounds(50, 50, 150, 20);
tf2 = new TextField();
tf2.setBounds(50, 100, 150, 20);
tf3 = new TextField();
tf3.setBounds(50, 150, 150, 20);
tf3.setEditable(false);
b1 = new Button("+");
b1.setBounds(50, 200, 50, 50);
b2 = new Button("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
add(tf1);
add(tf2);
add(tf3);
add(b1);
add(b2);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1 = tf1.getText();
String s2 = tf2.getText();
int a = Integer.parseInt(s1);
int b = Integer.parseInt(s2);
int c = 0;
if (e.getSource() == b1){
c = a + b;
}
else if (e.getSource() == b2){
c = a - b;
}
String result = String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample2();
}
}
output:
The text area allows us to type as much text as we want. When the text in the text
area becomes larger than the viewable area, the scroll bar appears automatically
which helps us to scroll the text up and down, or right and left.
4. TextArea (String text, int row, It constructs a new text area with the specified text in
the text area and specified number of rows and
int column)
columns.
Methods Inherited
Dimension preferredSize(int rows, int It determines the preferred size of a text area
8.
columns) with given number of rows and columns.
12. void setColumns(int columns) It sets the number of columns for this text area.
13. void setRows(int rows) It sets the number of rows for this text area.
import java.awt.*;
import java.awt.event.*;
public class TextAreaExample2 extends Frame implements ActionListener {
Label l1, l2;
TextArea area;
Button b;
TextAreaExample2() {
l1 = new Label();
l1.setBounds(50, 50, 100, 30);
l2 = new Label();
l2.setBounds(160, 50, 100, 30);
area = new TextArea();
area.setBounds(20, 100, 300, 300);
b = new Button("Count Words");
b.setBounds(100, 400, 100, 30);
b.addActionListener(this);
add(l1);
add(l2);
add(area);
add(b);
setSize(400, 450);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String text = area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
public static void main(String[] args) {
new TextAreaExample2();
} }
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".
Sr.
Constructor Description
no.
1. Checkbox() It constructs a checkbox with no string as the label.
Checkbox(String label, boolean It constructs a checkbox with the given label and
3.
state) sets the given state.
Checkbox(String label, boolean It constructs a checkbox with the given label, set
4.
state, CheckboxGroup group) the given state in the specified checkbox group.
Checkbox(String label,
It constructs a checkbox with the given label, in the
5. CheckboxGroup group, boolean
given checkbox group and set to the specified state.
state)
Sr.
Method name Description
no.
It adds the given item listener to get the item
1. void addItemListener(ItemListener IL)
events from the checkbox.
selected.
13. void removeItemListener(ItemListener l) the item listener doesn't receive item events
In the following example, we have created two checkboxes and adding them into
the Frame. Here, we are adding the ItemListener with the checkbox which displays
the state of the checkbox (whether it is checked or unchecked) using the
getStateChange() method.
import java.awt.*;
import java.awt.event.*;
public class CheckboxExample2 {
CheckboxExample2() {
Frame f = new Frame ("CheckBox Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java");
checkbox2.setBounds(100, 150, 50, 50);
f.add(checkbox1);
f.add(checkbox2);
f.add(label);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: " + (e.getStateChange()==1 ?"checked"
:"unchecked"));
}
});
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxExample2();
}
}
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.
import java.awt.*;
import java.awt.event.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, false);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1); f.add(checkBox2); f.add(label);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
checkBox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ checkbox: Checked");
}
});
checkBox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java checkbox: Checked");
}
});
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
Output:
Sr.
Method name Description
no.
1. void add(String item) It adds an item to the choice menu.
protected void
14. It processes the event on the choice.
processEvent(AWTEvent e)
18. void removeAll() It removes all the items from the choice menu.
21. void select(String str) menu to the item whose string value is equal to
In the following example, we are creating a choice menu with 5 items. Along with
that we are creating a button and a label. Here, we are adding an event to the
button component using addActionListener(ActionListener a) method i.e. the selected
item from the choice menu is displayed on the label when the button is clicked.
import java.awt.*;
import java.awt.event.*;
public class ChoiceExample2 {
ChoiceExample2() {
Frame f = new Frame();
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400, 100);
Button b = new Button("Show");
b.setBounds(200, 100, 50, 20);
final Choice c = new Choice();
c.setBounds(100, 100, 75, 75);
c.add("C");
c.add("C++");
c.add("Java");
c.add("PHP");
c.add("Android");
f.add(c);
f.add(label);
f.add(b);
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "+ c.getItem(c.getSelectedIndex());
label.setText(data);
}
});
}
public static void main(String args[])
{
new ChoiceExample2();
}
}
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.
Scrollbar ScrollPane
It is a component. It is a container.
It handles its own events and performs its
It does not handles its own events.
own scrolling.
Scrollbar cannot have a ScrollPane. ScrollPane can have a scrollbar.
ScrollPane
ScrollPane is a component that provides a scrollable view of another component. It
is often used when the content to be displayed is larger than the visible area. You
can add various components, such as panels or text areas, to a ScrollPane to make
them scrollable.
import java.awt.*;
panel.setLayout(new FlowLayout());
panel.add(button);
scrollPane.add(panel);
frame.add(scrollPane);
frame.setSize(300, 200);
frame.setVisible(true);
frame.addWindowListener(new java.awt.event.WindowAdapter() {
System.exit(0);
}
});
}}
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize
buttons but Dialog doesn't have.
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static Dialog d;
DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
Output:
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
import java.awt.*;
class MenuExample
{
MenuExample(){
Frame f= new Frame("Menu and MenuItem Example");
MenuBar mb=new MenuBar();
Menu menu=new Menu("Menu");
Menu submenu=new Menu("Sub Menu");
MenuItem i1=new MenuItem("Item 1");
MenuItem i2=new MenuItem("Item 2");
MenuItem i3=new MenuItem("Item 3");
MenuItem i4=new MenuItem("Item 4");
MenuItem i5=new MenuItem("Item 5");
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample();
}
}
Java AWT Graphics
Graphics is an abstract class provided by Java AWT which is used to draw or paint
on the components. It consists of various fields which hold information like
components to be painted, font, color, XOR mode, etc., and methods that allow
drawing various shapes on the GUI components. Graphics is an abstract class and
thus cannot be initialized directly. Objects of its child classes can be obtained in the
following two ways.
void paint(Graphics g)
void update(Graphics g)
Drawing shapes using Graphics Object
Line
The following method of Graphics class is used to draw the line:
int arcHeight)
• void fillRect(int x, int y, int width, int height)
• void fillRoundRect(int x, int y, int width, int height, int arcWidth, int
arcHeight)
Oval and Circle
The following methods are used to draw ovals and circles :
Arc
The following methods of Graphics class are used to draw arcs:
• void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle)
• void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle)
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
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.
Example
import java.awt.*;
import javax.swing.*;
public class Border
{
Border()
{
JFrame 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();
}
}
Output:
FlowLayout
This layout is used to arrange the GUI components in a sequential flow (that
means one after another in horizontal way)
You can also set flow layout of components like flow from left, flow from right.
FlowLayout Left
Frame f=new Frame();
f.setLayout(new FlowLayout(FlowLayout.LEFT));
FlowLayout Right
Frame f=new Frame();
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
Example
import java.awt.*;
import javax.swing.*;
public class MyFlowLayout
{
MyFlowLayout()
{
JFrame 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));
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new MyFlowLayout();
}
}
Output:
GridLayout
This layout is used to arrange the GUI components in the table format.
Example
import java.awt.*;
import javax.swing.*;
public class MyGridLayout
{
MyGridLayout()
{
JFrame f=new JFrame();
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));
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new MyGridLayout();
}
}
Output
CardLayout
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.
Output:
GridBagLayout
Fields
protected static int MINSIZE It is smallest grid that can be laid out by the
grid bag layout.
protected static int PREFERREDSIZE It is preferred grid size that can be laid out
by the grid bag layout.
Example
import java.awt.Button;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagLayoutExample extends JFrame
{
public static void main(String[] args)
{
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample()
{
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
this.setLayout(layout);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.ipady = 20;
gbc.gridx = 0;
gbc.gridy = 1;
this.add(new Button("Button Three"), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
this.add(new Button("Button Four"), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output: