0% found this document useful (0 votes)
11 views50 pages

Java Unit4

Uploaded by

vinodkethavath03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views50 pages

Java Unit4

Uploaded by

vinodkethavath03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Unit-4

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.

Delegation Event Model in Java


 The Delegation Event model is defined to handle events in GUI programming
languages. The GUI stands for Graphical User Interface, where a user
graphically/visually interacts with the system.
 The GUI programming is inherently event-driven; whenever a user initiates an
activity such as a mouse activity, clicks, scrolling, etc., each is known as an
event that is mapped to a code to respond to functionality to the user. This is
known as event handling.

The below image demonstrates the event processing.


In this model, a source generates an event and forwards it to one or more listeners.
The listener waits until it receives an event. Once it receives the event, it is
processed by the listener and returns it.

Basically, an Event Model is based on the following three components:


 Events
 Events Sources
 Events Listeners

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

Event Classes Description Listener


Interface

ActionEvent generated when button is pressed, menu-item ActionListener


is selected, list-item is double clicked

MouseEvent generated when mouse is dragged, MouseListener


moved,clicked,pressed or released and also
when it enters or exit a component

KeyEvent generated when input is received from KeyListener


keyboard

ItemEvent generated when check-box or list item is ItemListener


clicked

TextEvent generated when value of textarea or textfield TextListener


is changed

MouseWheelEvent generated when mouse wheel is moved MouseWheelListe


ner

WindowEvent generated when window is activated, WindowListener


deactivated, deiconified, iconified, opened or
closed

ComponentEvent generated when component is ComponentEvent


hidden,moved,resized orset visible Listener

ContainerEvent generated when component is added or ContainerListener


removed from container

AdjustmentEvent generated when scroll bar is manipulated AdjustmentListen


er

FocusEvent generated when component gains or loses FocusListener


keyboard focus

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)
{
}

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
 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 get executed and returns.

Syntax to Handle the Event


class className implements XXXListener
{
.......
.......
}
addcomponentobject.addXXXListener(this);
.......
// override abstract method of given interface and write proper logic
public void methodName(XXXEvent e)
{
.......
.......
}
.......
}

Event Handling for Mouse

For handling event for mouse you need MouseEvent class and MouseListener
interface.

GUI Component Event class Listener Interface


Mouse MouseEvent MouseListener

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.

Methods of MouseListener interface


The signature of 5 methods found in MouseListener interface are given below:
1. public abstract void mouseClicked(MouseEvent e);
2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);

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:

Event Handling for Keyboard


The Java KeyListener is notified whenever you change the state of key. It is notified
against KeyEvent. The KeyListener interface is found in java.awt.event package. It
has three methods.
Methods of KeyListener interface
1. public abstract void keyPressed(KeyEvent e);
2. public abstract void keyReleased(KeyEvent e);
3. public abstract void keyTyped(KeyEvent e);

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

 In a program, when a listener has many abstract methods to override, it


becomes complex for the programmer to override all of them.
 For example, for closing a frame, we must override seven abstract methods of
WindowListener, but we need only one method of them.
 For reducing complexity, Java provides a class known as "adapters" or adapter
class.
 Adapters are abstract classes, that are already being overriden.

Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapte HierarchyBoundsListener
r

Java WindowAdapter Example

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.

Java AWT components are platform-dependent i.e. components are displayed


according to the view of operating system. AWT is heavy weight i.e. its components
are using the resources of underlying operating system (OS).

The java.awt package provides classes for AWT API such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy

• Components: AWT provides various components such as buttons, labels, text


fields, checkboxes, etc used for creating GUI elements for Java Applications.

• Containers: AWT provides containers like panels, frames, and dialogues to


organize and group components in the Application.

• 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,

key presses, etc. using event listeners and adapters.


• Graphics and Drawing: It is the feature of AWT that helps to draw shapes,

insert images and write text in the components of a Java Application.

Types of Containers in Java AWT

There are four types of containers in Java AWT:


1.Window: Window is a top-level container that represents a graphical window or

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

be used for grouping other components together within a window or a frame.


3.Frame: The Frame is the container that contains the title bar and border and

can have menu bars.


4.Dialog: A dialog box is a temporary window an application creates to retrieve

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:

There are four types of containers in Java AWT:

1.Window 2.Panel 3.Frame 4.Dialog

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.

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.

Changes the visibility of the component, by default


public void setVisible(boolean status)
false.
To create simple AWT example, you need a frame. There are two ways to create a
GUI using Frame in AWT.

1.By extending Frame class (inheritance)

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

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.

AWT Label Class Declaration

1. public class Label extends Component implements Accessible

AWT Label Fields

The java.awt.Component class has following fields:

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.

Label class Constructors

Sr.no. Constructor Description


1. Label() It constructs an empty label.

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.

Label Class Methods

Sr. no. Method name Description


1. void setText(String text) It sets the texts for label with the specified text.

It sets the alignment for label with the specified


2. void setAlignment(int alignment)
alignment.

3. String getText() It gets the text of the label

4. int getAlignment() It gets the current alignment of the label.

5. void addNotify() It creates the peer for the label.

6. AccessibleContext getAccessibleContext() It gets the Accessible Context associated with


the label.

7. protected String paramString() It returns the string the state of the label.

Method inherited

The above methods are inherited by the following classes:

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

Java AWT Button Class methods


List of all the methods associated with the AWT button and its Description
Method Description

The action listener is added to receive action events from this


void addActionListener(ActionListener l)
button.

The method returns an array of all the action listeners that


ActionListener[] getActionListeners()
have been registered on this button.

String getLabel() Retrieves the label of this button.

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;

public class Main {

public static void main(String[] args)


{

Frame frame = new Frame("AWT Button Example");

// Create a button

Button button = new Button("Click Me!");

// Set the button position on the frame

button.setBounds(150, 130, 100, 30);

frame.add(button); // Add the button to the frame

// Set the frame size and layout

frame.setSize(400, 300);

frame.setLayout(null);

frame.setVisible(true); // Set the frame visibility to true

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.*;

public class Main {


public static void main(String[] args)
{
// Create a frame
Frame frame = new Frame("AWT Button Example");
// Create a button
Button b = new Button("Click Here!");

// Set the position of the button


b.setBounds(160, 80, 80, 40);

// Add a background color


b.setBackground(Color.GREEN);

// Create a label
Label label = new Label();

// Set the position of the label


label.setBounds(80, 140, 280, 20);

// Set the properties of the label


label.setForeground(Color.BLUE);
label.setFont(new Font("Arial", Font.BOLD, 14));

// Add an action listener to the button


b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
label.setText( "Hey geek, Welcome to JBREC");
}
});
frame.add(b);

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.

AWT Scrollbar Class Declaration

1. public class Scrollbar extends Component implements Adjustable, Accessible

Scrollbar Class Fields

The fields of java.awt.Image class are as follows:

• static int HORIZONTAL - It is a constant to indicate a horizontal scroll bar.

• static int VERTICAL - It is a constant to indicate a vertical scroll bar.

Scrollbar Class Constructors

Sr.
Constructor Description
no.
1 Scrollbar() Constructs a new vertical scroll bar.

Constructs a new scroll bar with the specified


2 Scrollbar(int orientation)
orientation.

Scrollbar(int orientation, int Constructs a new scroll bar with the specified

3 value, int visible, int orientation, initial value, visible amount, and

minimum, int maximum) minimum and maximum values.


Where the parameters,

•orientation: specifiey whether the scrollbar will be horizontal or vertical.

•Value: specify the starting position of the knob of Scrollbar on its track.

•Minimum: specify the minimum width of track on which scrollbar is moving.

•Maximum: specify the maximum width of track on which scrollbar is moving.


Scrollbar Listener

void addAdjustmentListener (AdjustmentListener l) - It adds the given


adjustment listener to receive instances of AdjustmentEvent from the scroll bar.

Example :

s.addAdjustmentListener(new AdjustmentListener() {

public void adjustmentValueChanged(AdjustmentEvent e) {


label.setText("Vertical Scrollbar value is:"+ s.getValue());
}
});

Java AWT Scrollbar Example


In the following example, we are creating a scrollbar using the Scrollbar() and
adding it into the Frame.

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.

AWT TextField Class Declaration

public class TextField extends TextComponent

Sr.
Constructor Description
no.
1. TextField() It constructs a new text field component.

It constructs a new text field initialized with the given


2. TextField(String text)
string text to be displayed.

It constructs a new textfield (empty) with given number of


3. TextField(int columns)
columns.

TextField(String text, int It constructs a new text field with the given text and given
4.
columns) number of columns (width).

TextField Class Methods


Sr.
Method name Description
no.
1 void addNotify() It creates the peer of text field.

It adds the specified action listener to receive


2 void addActionListener(ActionListener l)
action events from the text field.

3 Dimension getPreferredSize() It fetches the preferred size of the text field.

It fetches the preferred size of the text field


4 Dimension getPreferredSize(int columns)
with specified number of columns.

5 protected String paramString() It returns a string representing state of the


text field.

It processes action events occurring in the text


protected void
6 field by dispatching them to a registered
processActionEvent(ActionEvent e)
ActionListener object.

7 protected void processEvent(AWTEvent e) It processes the event on text field.

void removeActionListener(ActionListener It removes specified action listener so that it


8
l) doesn't receive action events anymore.

9 void setColumns(int columns) It sets the number of columns in text field.

It sets the text presented by this text


10 void setText(String t)
component to the specified text.

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:

Java AWT TextArea


The object of a TextArea class is a multiline region that displays text. It allows the
editing of multiple line text. It inherits TextComponent class.

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.

AWT TextArea Class Declaration

1. public class TextArea extends TextComponent


Class constructors:
Sr.
Constructor Description
no.
It constructs a new and empty text area with no text in
1. TextArea()
it.

It constructs a new text area with specified number of


2. TextArea (int row, int column)
rows and columns and empty string as text.

It constructs a new text area and displays the specified


3. TextArea (String text)
text in it.

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.

It construcst a new text area with specified text in text


TextArea (String text, int row,
5. area and specified number of rows and columns and
int column, int scrollbars)
visibility.

Methods Inherited

The methods of TextArea class are inherited from following classes:


Sr.
Method name Description
no.
1. void addNotify() It creates a peer of text area.

It appends the specified text to the current text


2. void append(String str)
of text area.

AccessibleContext It returns the accessible context related to the


3.
getAccessibleContext() text area

4. int getColumns() It returns the number of columns of text area.

5. Dimension getMinimumSize() It determines the minimum size of a text area.

Dimension getMinimumSize(int rows, It determines the minimum size of a text area


6.
int columns) with the given number of rows and columns.

7. Dimension getPreferredSize() It determines the preferred size of a text area.

Dimension preferredSize(int rows, int It determines the preferred size of a text area
8.
columns) with given number of rows and columns.

9. int getRows() It returns the number of rows of text area.

It returns an enumerated value that indicates


10. int getScrollbarVisibility()
which scroll bars the text area uses.

It inserts the specified text at the specified


11. void insert(String str, int pos)
position in this text area.

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.

Java AWT TextArea Example with ActionListener

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

AWT Checkbox Class Declaration

1. public class Checkbox extends Component implements ItemSelectable, Accessible

Checkbox Class Constructors

Sr.
Constructor Description
no.
1. Checkbox() It constructs a checkbox with no string as the label.

2. Checkbox(String label) It constructs a checkbox with the given 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)

Checkbox Class Methods

Sr.
Method name Description
no.
It adds the given item listener to get the item
1. void addItemListener(ItemListener IL)
events from the checkbox.

2. AccessibleContext getAccessibleContext() It fetches the accessible context of checkbox.

3. void addNotify() It creates the peer of checkbox.

4. CheckboxGroup getCheckboxGroup() It determines the group of checkbox.

It returns an array of the item listeners


5. ItemListener[] getItemListeners()
registered on checkbox.

6. String getLabel() It fetched the label of checkbox.

It returns an array of all the objects registered


7. T[] getListeners(Class listenerType)
as FooListeners.
It returns an array (size 1) containing checkbox

8. Object[] getSelectedObjects() label and returns null if checkbox is not

selected.

It returns true if the checkbox is on, else


9. boolean getState()
returns off.

It returns a string representing the state of


10. protected String paramString()
checkbox.

protected void processEvent(AWTEvent


11. It processes the event on checkbox.
e)

It process the item events occurring in the


protected void
12. checkbox by dispatching them to registered
processItemEvent(ItemEvent e)
ItemListener object.

It removes the specified item listener so that

13. void removeItemListener(ItemListener l) the item listener doesn't receive item events

from the checkbox anymore.

void setCheckboxGroup(CheckboxGroup It sets the checkbox's group to the given


14.
g) checkbox.

It sets the checkbox's label to the string


15. void setLabel(String label)
argument.

It sets the state of checkbox to the specified


16. void setState(boolean state)
state.

Java AWT Checkbox Example with ItemListener

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.

AWT CheckboxGroup Class Declaration

public class CheckboxGroup extends Object implements Serializable

Java AWT CheckboxGroup Example with ItemListener

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:

Java AWT Choice


The object of Choice class is used to show popup menu of choices. Choice selected
by user is shown on the top of a menu. It inherits Component class.

AWT Choice Class Declaration

1. public class Choice extends Component implements ItemSelectable, Accessible

Choice Class constructor

Sr. no.Constructor Description


1. Choice() It constructs a new choice menu.

Sr.
Method name Description
no.
1. void add(String item) It adds an item to the choice menu.

It adds the item listener that receives item


2. void addItemListener(ItemListener l)
events from the choice menu.

3. void addNotify() It creates the peer of choice.

It gets the item (string) at the given index


5. String getItem(int index)
position in the choice menu.

It returns the number of items of the choice


6. int getItemCount()
menu.

It returns an array of all item listeners registered


7. ItemListener[] getItemListeners()
on choice.

9. int getSelectedIndex() Returns the index of the currently selected item.


Gets a representation of the current choice as a
10. String getSelectedItem()
string.

Inserts the item into this choice at the specified


12. void insert(String item, int index)
position.

protected void
14. It processes the event on the choice.
processEvent(AWTEvent e)

Processes item events occurring on this Choice


protected void processItemEvent
15. menu by dispatching them to any registered
(ItemEvent e)
ItemListener objects.

It removes an item from the choice menu at the


16. void remove(int position)
given index position.

It removes the first occurrence of the item from


17. void remove(String item)
choice menu.

18. void removeAll() It removes all the items from the choice menu.

It removes the mentioned item listener. Thus is


void removeItemListener (ItemListener
19. doesn't receive item events from the choice
l)
menu anymore.

It changes / sets the selected item in the choice


20. void select(int pos)
menu to the item at given index position.

It changes / sets the selected item in the choice

21. void select(String str) menu to the item whose string value is equal to

string specified in the argument.

Java AWT Choice Example with ActionListener

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.

It doesn't have title bar.

AWT Panel class declaration

public class Panel extends Container implements Accessible


import java.awt.*;
public class PanelExample {
PanelExample()
{
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}
Output:
What is the difference between a Scrollbar and a ScrollPane?

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.*;

public class ScrollPaneExample {

public static void main(String[] args) {

Frame frame = new Frame("ScrollPane Example");

Panel panel = new Panel();

panel.setLayout(new FlowLayout());

for (int i = 1; i <= 10; i++) {

Button button = new Button("Button " + i);

panel.add(button);

ScrollPane scrollPane = new ScrollPane();

scrollPane.add(panel);

frame.add(scrollPane);

frame.setSize(300, 200);

frame.setVisible(true);

frame.addWindowListener(new java.awt.event.WindowAdapter() {

public void windowClosing(java.awt.event.WindowEvent windowEvent) {

System.exit(0);

}
});

}}

We create a Panel and set its layout to FlowLayout.

1. Inside the panel, we add ten buttons to demonstrate a scrollable content.


2. We create a ScrollPane and add the panel to it using the add() method.
3. Finally, we add the ScrollPane to a Frame and set some basic properties for
the frame.
When you run this program, you will see a window with a scrollable panel
containing ten buttons. If the content is too large to fit in the visible area, the
ScrollPane will provide scrollbars to navigate through the content.

Java AWT Dialog


The Dialog control represents a top level window with a border and a title used to
take some form of input from the user. It inherits the Window class.

Unlike Frame, it doesn't have maximize and minimize buttons.

Frame vs Dialog

Frame and Dialog both inherits Window class. Frame has maximize and minimize
buttons but Dialog doesn't have.

AWT Dialog class declaration

public class Dialog extends Window

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:

Java AWT MenuItem and Menu


The object of MenuItem class adds a simple labeled menu item on menu. The items
used in a menu must belong to the MenuItem or any of its subclass.

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

public class MenuItem extends MenuComponent implements Accessible

AWT Menu class declaration

public class Menu extends MenuItem implements MenuContainer, Accessible

Java AWT MenuItem and Menu Example

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.

1. Inside paint() or update() method


It is passed as an argument to paint and update methods and therefore can be
accessed inside these methods. paint() and update() methods are present in the
Component class and thus can be overridden for the component to be painted.

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:

void drawLine(int startX, int startY, int endX, int endY)


Rectangle
The following methods of Graphics class are used to draw rectangles:

• void drawRect(int x, int y, int width, int height)

• void drawRoundRect(int x, int y, int width, int height, int arcWidth,

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 :

• void drawOval(int x, int y, int width, int height)

• void fillOval(int x, int y, int width, int height)

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;

public class MyFrame extends Frame {


public MyFrame()
{
setVisible(true);
setSize(300, 200);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void paint(Graphics g)
{
g.drawRect(100, 100, 100, 50);
}

public static void main(String[] args)


{
new MyFrame();
}
}
Output:
Java 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:


1. BorderLayout
2. FlowLayout
3. GridLayout
4. CardLayout
5. GridBagLayout

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

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();

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));
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.

Constructors of CardLayout class


1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal
and vertical gap.

Commonly used methods of CardLayout class


1. public void next(Container parent): is used to flip to the next card of the given
container.
2. public void previous(Container parent): is used to flip to the previous card of the
given container.
3. public void first(Container parent): is used to flip to the first card of the given
container.
4. public void last(Container parent): is used to flip to the last card of the given
container.
5. 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);
} }

Output:
GridBagLayout

 The Java GridBagLayout class is used to align components vertically,


horizontally or along their baseline.
 The components may not be of same size. Each GridBagLayout object maintains
a dynamic, rectangular grid of cells. Each component occupies one or more
cells known as its display area. Each component associates an instance of
GridBagConstraints. With the help of constraints object we arrange component's
display area on the grid. The GridBagLayout manages each component's
minimum and preferred sizes in order to determine component's size.

Fields

Modifier and Type Field Description

double[] columnWeights It is used to hold the overrides to the


column weights.

int[] columnWidths It is used to hold the overrides to the


column minimum width.

protected comptable It is used to maintains the association


Hashtable<Component, between a component and its gridbag
GridBagConstraints> constraints.

protected defaultConstraints It is used to hold a gridbag constraints


GridBagConstraints instance containing the default values.

protected layoutInfo It is used to hold the layout information for


GridBagLayoutInfo the gridbag.

protected static int MAXGRIDSIZE No longer in use just for backward


compatibility

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.

int[] rowHeights It is used to hold the overrides to the row


minimum heights.

double[] rowWeights It is used to hold the overrides to the row


weights.
Useful Methods

Modifier and Method Description


Type

void addLayoutComponent(Component It adds specified component to the


comp, Object constraints) layout, using the specified
constraints object.

void addLayoutComponent(String It has no effect, since this layout


name, Component comp) manager does not use a per-
component string.

protected void AdjustForGravity( It adjusts the x, y, width, and


GridBagConstraints constraints, height fields to the correct values
Rectangle r) depending on the constraint
geometry and pads.

protected void arrangeGrid(Container parent) Lays out the grid.

protected void ArrangeGrid(Container parent) This method is obsolete and supplied


for backwards compatibility

GridBagConstrain getConstraints(Component comp) It is for getting the constraints for


ts the specified component.

float getLayoutAlignmentX(Container It returns the alignment along the x


parent) axis.

float getLayoutAlignmentY(Container It returns the alignment along the y


parent) axis.

int[][] getLayoutDimensions() It determines column widths and


row heights for the layout grid.

protected getLayoutInfo(Container parent, This method is obsolete and supplied


GridBagLayoutInf int sizeflag) for backwards compatibility.
o

protected GetLayoutInfo(Container parent, This method is obsolete and supplied


GridBagLayoutInf int sizeflag) for backwards compatibility.
o

Point getLayoutOrigin() It determines the origin of the layout


area, in the graphics coordinate
space of the target container.

double[][] getLayoutWeights() It determines the weights of the


layout grid's columns and rows.

protected getMinSize(Container parent, It figures out the minimum size of


Dimension GridBagLayoutInfo info) the master based on the information
from getLayoutInfo.

protected GetMinSize(Container parent, This method is obsolete and supplied


Dimension GridBagLayoutInfo info) for backwards compatibility only

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:

You might also like