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

Java AWT and Swing

The document discusses the AWT (Abstract Windowing Toolkit) API in Java, which provides basic GUI components. It covers that AWT was introduced in JDK 1.0 but most components are now obsolete and replaced by Swing. It also summarizes the commonly used AWT packages, container classes, component classes, and how to construct and add components to containers to build GUI applications.

Uploaded by

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

Java AWT and Swing

The document discusses the AWT (Abstract Windowing Toolkit) API in Java, which provides basic GUI components. It covers that AWT was introduced in JDK 1.0 but most components are now obsolete and replaced by Swing. It also summarizes the commonly used AWT packages, container classes, component classes, and how to construct and add components to containers to build GUI applications.

Uploaded by

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

AWT – Application Windowing Toolkit

There are two sets of Java APIs for graphics programming: AWT (Abstract Windowing Toolkit) and Swing.
1. AWT API was introduced in JDK 1.0. Most of the AWT components have become obsolete and
should be replaced by newer Swing components.
2. Swing API, a much more comprehensive set of graphics libraries that enhances the AWT, was
introduced as part of Java Foundation Classes (JFC) after the release of JDK 1.1. JFC consists of Swing,
Java2D, Accessibility, Internationalization, and Pluggable Look-and-Feel Support APIs. JFC was an
add-on to JDK 1.1 but has been integrated into core Java since JDK 1.2.
Other than AWT/Swing Graphics APIs provided in JDK, others have also provided Graphics APIs that work with
Java, such as Eclipse's Standard Widget Toolkit (SWT) (used in Eclipse), Google Web Toolkit (GWT) (used in
Android), 3D Graphics API such as Java bindings for OpenGL (JOGL) and Java3D.

Programming GUI with AWT


Java Graphics APIs - AWT and Swing - provide a huge set of reusable GUI components, such as button, text
field, label, choice, panel and frame for building GUI applications. You can simply reuse these classes rather
than re-invent the wheels. I shall start with the AWT classes before moving into Swing to give you a complete
picture. I have to stress that AWT component classes are now obsoleted by Swing's counterparts.

AWT Packages
AWT is huge! It consists of 12 packages (Swing is even bigger, with 18 packages as of JDK 1.7!). Fortunately,
only 2 packages - java.awt andjava.awt.event - are commonly-used.

1. The java.awt package contains the core AWT graphics classes:


▪ GUI Component classes (such as Button, TextField, and Label),
▪ GUI Container classes (such as Frame, Panel, Dialog and ScrollPane),
▪ Layout managers (such as FlowLayout, BorderLayout and GridLayout),
2. Custom graphics classes (such as Graphics, Color and Font).

The java.awt.event package supports event handling:

▪ Event classes (such as ActionEvent, MouseEvent, KeyEvent and WindowEvent),


▪ Event Listener Interfaces (such
as ActionListener, MouseListener, KeyListener and WindowListener),
▪ Event Listener Adapter classes (such as MouseAdapter, KeyAdapter, and WindowAdapter).
AWT provides a platform-independent and device-independent interface to develop graphic programs that
runs on all platforms, such as Windows, Mac, and Linux.

Containers and Components

There are two types of GUI elements:


1. Component: Components are elementary GUI entities (such as Button, Label, and TextField)
2. Container: Containers (such as Frame, Panel and Applet) are used to hold components in a specific
layout (such as flow or grid). A container can also hold sub-containers.

GUI components are also called controls (Microsoft ActiveX Control), widgets (Eclipse's Standard Widget
Toolkit, Google Web Toolkit), which allow users to interact with (i.e., control) the application through these
components (such as button-click and text-entry).

In the above figure, there are three containers: a Frame and two Panels. A Frame is the top-level container of
an AWT program.

A Frame has a title bar (containing an icon, a title, and the minimize/maximize/close buttons), an optional
menu bar and the content display area.

A Panel is a rectangular area used to group related GUI components in a certain layout. In the above figure,
the top-level Frame contains two Panels. There are five components: aLabel (providing description),
a TextField (for users to enter text), and three Buttons (for user to trigger certain programmed actions).

In a GUI program, a component must be kept in a container. You need to identify a container to hold the
components. Every container has a method called add(Component c). A container (say aContainer) can
invoke aContainer.add(aComponent) to add aComponent into itself. For example,

Panel panel = new Panel(); // Panel is a Container


Button btn = new Button("Press"); // Button is a Component
panel.add(btn); // The Panel Container adds a Button Component
AWT Container Classes
Top-Level Containers: Frame, Dialog and Applet
Each GUI program has a top-level container. The commonly-used top-level containers in AWT
are Frame, Dialog and Applet:

A Frame provides the "main window" for the GUI application, which has a title bar (containing an icon, a title,
the minimize, maximize/restore-down and close buttons), an optional menu bar, and the content display area.
To write a GUI program, we typically start with a subclass extending fromjava.awt.Frame to inherit the main
window as follows:

import java.awt.Frame; // Using Frame class in package java.awt

// A GUI program is written as a subclass of Frame - the top-level container


// This subclass inherits all properties from Frame, e.g., title, icon,
buttons, content-pane
public class MyGUIProgram extends Frame {

// Constructor to setup the GUI components


public MyGUIProgram() { ...... }

// Other methods
......
......

// The entry main() method


public static void main(String[] args) {
// Invoke the constructor (to setup the GUI) by allocating an instance
new MyGUIProgram();
}
}

An AWT Dialog is a "pop-up window" used for interacting with the users. A Dialog has a title-bar (containing
an icon, a title and a close button) and a content display area, as illustrated.

An AWT Applet (in package java.applet) is the top-level container for an applet, which is a Java program
running inside a browser. Applet will be discussed in the later chapter.

Secondary Containers: Panel and ScrollPane


Secondary containers are placed inside a top-level container or another secondary container. AWT also provide
these secondary containers:

1. Panel: a rectangular box under a higher-level container, used to layout a set of related GUI
components in pattern such as grid or flow.
2. ScrollPane: provides automatic horizontal and/or vertical scrolling for a single child component.
3. others.

Hierarchy of the AWT Container Classes


The hierarchy of the AWT Container classes is as follows:

As illustrated, each Container has a layout.


AWT Component Classes
AWT provides many ready-made and reusable GUI components. The frequently-used
are: Button, TextField, Label, Checkbox, CheckboxGroup(radio buttons), List, and Choice

Label
A java.awt.Label provides a text description message.

Constructors
public Label(String strLabel, int alignment); // Construct a Label with the
given text String, of the text alignment
public Label(String strLabel); // Construct a Label with the
given text String
public Label();

The Label class has three constructors:


1. The first constructor constructs a Label object with the given text string in the given alignment. Note
that three static constants Label.LEFT,Label.RIGHT, and Label.CENTER are defined in the class for
you to specify the alignment (rather than asking you to memorize arbitrary integer values).
2. The second constructor constructs a Label object with the given text string in default of left-aligned.
3. The third constructor constructs a Label object with an initially empty string. You could set the label
text via the setText() method later.

Constants
public static final LEFT; // Label.LEFT
public static final RIGHT; // Label.RIGHT
public static final CENTER; // Label.CENTER

Public Methods
// Examples
public String getText();
public void setText(String strLabel);
public int getAlignment();
public void setAlignment(int alignment);
The getText() and setText() methods can be used to read and modify the Label's text.
the getAlignment() and setAlignment()methods can be used to retrieve and modify the alignment of the
text.

Constructing a Component and Adding the


Component into a Container
Three steps are necessary to create and place a GUI component:
1. Declare the component with an identifier (name);
2. Construct the component by invoking an appropriate constructor via the new operator;
3. Identify the container (such as Frame or Panel) designed to hold this component. The container can then
add this component onto itself via Container.add(aComponent) method. Every container has
add(Component) method. Take note that it is the container that actively and explicitly adds a component
onto itself, instead of the other way.

Example
Label lblInput;
// Declare an Label instance called lblInput
lblInput = new Label("Enter ID");
// Construct by invoking a constructor via the new operator
add(lblInput);
// this.add(lblInput) - "this" is typically a subclass of Frame
lblInput.setText("Enter password");
// Modify the Label's text string
lblInput.getText();
// Retrieve the Label's text string

An Anonymous Instance
You can create a Label without specifying an identifier, called anonymous instance. In the case, the Java
compiler will assign an anonymous identifier for the allocated object. You will not be able to reference an
anonymous instance in your program after it is created. This is usually alright for a Label instance as there is
often no need to reference a Label after it is constructed.

Example
// Allocate an anonymous Label instance. "this" container adds the instance
into itself.
// You CANNOT reference an anonymous instance to carry out further operation

add(new Label("Enter Name: ", Label.RIGHT));


// Same as
Label lblXxx = new Label("Enter Name: ", Label.RIGHT)); // lblXxx assigned by
compiler
add(lblXxx);

Program LabelDemo

import java.awt.*;

class MyFrame1 extends Frame


{
Label label1, label2, label3;

public MyFrame1()
{

label1 = new Label();


label1.setText("This is My Label1");

label2 = new Label("This is Label2");


label3 = new Label("This is Label3",Label.RIGHT );

setLayout(new FlowLayout(FlowLayout.LEFT));
add(label1);
add(label2);
add(label3);
System.out.println("Label1 = " + label1.getText());

setTitle("This is Title");
setSize(300, 200);
setVisible(true);
}
}

public class LabelDemo1


{
public static void main(String[] args)
{
new MyFrame1();
}
}
Button
A java.awt.Button is a GUI component that triggers a certain programmed action upon clicking

Constructors
public Button(String buttonLabel);
// Construct a Button with the given label
public Button();
// Construct a Button with empty label
The Button class has two constructors. The first constructor creates a Button object with the given label
painted over the button. The second constructor creates a Button object with no label.

Public Methods
public String getLabel();
// Get the label of this Button instance
public void setLabel(String buttonLabel);
// Set the label of this Button instance
public void setEnable(boolean enable);
// Enable or disable this Button. Disabled Button cannot be clicked.

The getLabel() and setLabel() methods can be used to read the current label and modify the label of a
button, respectively.

Note: The latest Swing's JButton replaces getLabel()/setLabel() with getText()/setText() to be consistent with all
the components. We will describe Swing later.

Event
Clicking a button fires a ActionEvent and triggers a certain programmed action.

TextField
A java.awt.TextField is single-line text box for users to enter texts. Hitting the "ENTER" key on
a TextField object triggers an ActionEvent.

Constructors
public TextField(String strInitialText, int columns);
// Construct a TextField instance with the given initial text string with the number of
columns.

public TextField(String strInitialText);


// Construct a TextField instance with the given initial text string.

public TextField(int columns);


// Construct a TextField instance with the number of columns.

Public Methods
public String getText();
// Get the current text on this TextField instance

public void setText(String strText);


// Set the display text on this TextField instance

public void setEditable(boolean editable);


// Set this TextField to editable (read/write) or non-editable (read-only)

Event
Hitting the "ENTER" key on a TextField fires a ActionEvent, and triggers a certain programmed action.

Example
TextField tfInput = new TextField(30);
// Declare and allocate an TextField instance called tfInput

add(tfInput);
// "this" Container adds the TextField

TextField tfResult = new TextField();


// Declare and allocate an TextField instance called tfResult

tfResult.setEditable(false) ;
// Set to read-only

add(tfResult); /
/ "this" Container adds the TextField
......
// Read an int from TextField "tfInput", square it, and display on "tfResult".
// getText() returns a String, need to convert to int

int number = Integer.parseInt(tfInput.getText());


number *= number;
// setText() requires a String, need to convert the int number to String.
tfResult.setText(number + "");

Take note that getText()/SetText() operates on String. You can convert a String to a primitive, such
as int or double via static methodInteger.parseInt() or Double.parseDouble(). To convert a primitive
to a String, simply concatenate the primitive with an empty String.

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

class MyFrame extends Frame


{
TextField txt1,txt2, txt3;
Label label1, label2, label3;
Panel panel1;

public MyFrame()
{
panel1 = new Panel();

label1 = new Label("Enter A :");


txt1 = new TextField("0", 20);

label2 = new Label("Enter B :");


txt2 = new TextField("0", 20);

label3 = new Label("Result :");


txt3 = new TextField(20);
txt3.setEditable(false);

setFont(new Font("calibri", 0, 20));


panel1.setLayout(new GridLayout(3,2));
panel1.add(label1);
panel1.add(txt1);

panel1.add(label2);
panel1.add(txt2);

panel1.add(label3);
panel1.add(txt3);

setLayout(new FlowLayout());
add(panel1);

setSize(800, 600);
setVisible(true);
}
}
public class FrameDemo
{
public static void main(String[] args)
{
MyFrame f = new MyFrame();
}
}

Handle Button Click


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

class MyFrame extends Frame


{
TextField txt1,txt2, txt3;
Label label1, label2, label3;
Button btn1, btn2;
Panel panel1;

public MyFrame()
{
panel1 = new Panel();

label1 = new Label("Enter A :");


txt1 = new TextField("0", 20);

label2 = new Label("Enter B :");


txt2 = new TextField("0", 20);

label3 = new Label("Result :");


txt3 = new TextField(20);
txt3.setEditable(false);

btn1 = new Button("Addition");


btn2 = new Button("Subtraction");

setFont(new Font("calibri", 0, 20));


panel1.setLayout(new GridLayout(4,2));
panel1.add(label1);
panel1.add(txt1);

panel1.add(label2);
panel1.add(txt2);

panel1.add(btn1);
panel1.add(btn2);

btn1.addActionListener(new ButtonHandler());
btn2.addActionListener(new ButtonHandler());

panel1.add(label3);
panel1.add(txt3);

setLayout(new FlowLayout());
add(panel1);

setSize(800, 600);
setVisible(true);
}

public class ButtonHandler implements ActionListener


{
public void actionPerformed(ActionEvent e)
{
int n1 = Integer.parseInt(txt1.getText());
int n2 = Integer.parseInt(txt2.getText());
int ans = 0;
String str = e.getActionCommand();

switch(str)
{
case "Addition":
ans = n1+n2;
break;

case "Subtraction":
ans = n1-n2;
break;

default:
break;
}

txt3.setText(ans+"");
} -----
}
}

public class FrameDemo


{
public static void main(String[] args)
{
MyFrame f = new MyFrame();
}
}
Steps for Event Handling
Create Source Objects
The source object (such as Button and Textfield) interacts with the user. Upon triggered, it creates
an event object. This event object will be messaged to all the registered listener object(s), and an appropriate
event-handler method of the listener(s) is called-back to provide the response.

In other words, triggering a source fires an event to all its listener(s), and invoke an appropriate handler of the
listener(s).

To express interest for a certain source's event, the listener(s) must be registered with the source. In other
words, the listener(s) "subscribes" to a source's event, and the source "publishes" the event to all its
subscribers upon activation. This is known as subscribe-publish or observable-observerdesign pattern.

Register the Listener

Clicking a Button (or hitting the "Enter" key on a TextField) fires an ActionEvent to all
its ActionEvent listener(s).

An ActionEvent must implement ActionListener interface, which has


one abstract method actionPerformed() as follow:

public interface ActionListener {


public void actionPerformed(ActionEvent e);
// Called back upon button-click (on Button), enter-key pressed (on
TextField)
}
The source object (Button) registers listener via the addActionListener()

btnCount.addActionListener(this);

Note that addActionListener() takes an argument of the type ActionListener. "this", which
implements ActionListener interface (i.e., a subclass of ActionListener), is upcasted and passed to
the addActionListener() method.

Upon button-click, the btnCount creates an ActionEvent object, and calls back
the actionPerformed(ActionEvent) method of all its registered listener(s) with the ActionEvent object
created:
WindowEvent and WindowListener Interface
A WindowEvent is fired (to all its WindowEventlisteners) when a window (e.g., Frame) has been
opened/closed, activated/deactivated, iconified/deiconified via the 3 buttons at the top-right corner or
other means.
The source of WindowEvent shall be a top-level window-container such as Frame.

A WindowEvent listener must implement WindowListener interface, which declares 7 abstract event-
handling methods, as follows. Among them, thewindowClosing(), which is called back upon clicking the
window-close button, is the most commonly-used.

public void windowClosing(WindowEvent e)


// Called-back when the user attempts to close the window by clicking the window close button.
// This is the most-frequently used handler.
public void windowOpened(WindowEvent e)
// Called-back the first time a window is made visible.
public void windowClosed(WindowEvent e)
// Called-back when a window has been closed as the result of calling dispose on the window.
public void windowActivated(WindowEvent e)
// Called-back when the Window is set to be the active Window.
public void windowDeactivated(WindowEvent e)
// Called-back when a Window is no longer the active Window.
public void windowIconified(WindowEvent e)
// Called-back when a window is changed from a normal to a minimized state.
public void windowDeiconified(WindowEvent e)
// Called-back when a window is changed from a minimized to a normal state.

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

class MyFrame extends Frame implements WindowListener, ActionListener


{
Button btnExit;

public MyFrame(String title)


{
btnExit = new Button("Exit");

setLayout(new FlowLayout(FlowLayout.RIGHT));
add(btnExit);

addWindowListener(this);
btnExit.addActionListener(this);

setTitle(title);
setVisible(true);
setSize(400,400);
}

public void actionPerformed(ActionEvent e)


{
System.exit(1);
}

public void windowClosing(WindowEvent w)


{
System.exit(1);
}
public void windowOpened(WindowEvent w)
{
}
public void windowClosed(WindowEvent w)
{
}
public void windowActivated(WindowEvent w)
{
}
public void windowDeactivated(WindowEvent w)
{
}
public void windowIconified(WindowEvent w)
{
}
public void windowDeiconified(WindowEvent w)
{
}

public class WindowEventDemo


{
public static void main(String[] args)
{
new MyFrame("Window Event Demo");
}
}
Adapter Classes
Generally when a java class implements an interface, it has to provide implementation for all the methods
which are declared abstract in that interface.

An Adapter class is a class which contains empty implementations for the listener interface methods.
Therefore, a java class can inherit any adapter class and then it can implement / override the required method

Refer to the WindowEventDemo, a WindowEvent listener is required to implement


the WindowListener interface, which declares 7 abstract methods. Although we are only interested
inwindowClosing(), we need to provide an empty body to the other 6 methods in order to compile the
program. This is tedious.

Example : An adapter class called WindowAdapter is therefore provided, which implements


the WindowListener interface and provides default implementations to all the 7 abstract methods.
You can then derive a subclass from WindowAdapter and override only methods of interest and leave
the rest to their default implementation. For example,

Other Event-Listener Adapter Classes


Similarly, adapter classes such as MouseAdapter, MouseMotionAdapter, KeyAdapter, FocusAdapter are
available for MouseListener, MouseMotionListener, KeyListener, andFocusListener, respectively.

There is no ActionAdapter for ActionListener, because there is only one abstract method
(i.e. actionPerformed()) declared in the ActionListener interface. This method has to be overridden
and there is no need for an adapter.

The Adapter for listener interfaces are

Interface Adapter Class


MouseListener MouseAdapter
MouseMotionListener MouseMotionAdapter
WindowListener WindowAdapter
KeyListener KeyAdapter
ItemListener ItemAdapter
import java.awt.*;
import java.awt.event.*;

class MyFrame extends Frame implements ActionListener


{
Button btnExit;

public MyFrame(String title)


{
btnExit = new Button("Exit");

setLayout(new FlowLayout(FlowLayout.RIGHT));
add(btnExit);

addWindowListener(new MyWindow());
btnExit.addActionListener(this);

setTitle(title);
setVisible(true);
setSize(400,400);
}

public void actionPerformed(ActionEvent e)


{
System.exit(1);
}

class MyWindow extends WindowAdapter


{
public void windowClosing(WindowEvent w)
{
System.exit(1);
}
}

public class WindowEventDemo


{
public static void main(String[] args)
{
new MyFrame("Window Event Demo");
}
}
Event Delegation Model
According to this model, the GUI design is performed by one class and the event handling is performed by
another class (Adapter class)

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

class MyFrame extends Frame implements ActionListener


{
Button btnExit;

public MyFrame(String title)


{
btnExit = new Button("Exit");

setLayout(new FlowLayout(FlowLayout.RIGHT));
add(btnExit);

addWindowListener(new MyWindow(this));
btnExit.addActionListener(this);

setTitle(title);
setVisible(true);
setSize(400,400);
}

public void actionPerformed(ActionEvent e)


{
System.exit(1);
}
}

class MyWindow extends WindowAdapter


{
MyFrame frm1;

public MyWindow(MyFrame f)
{
frm1 = f;
}
public void windowClosing(WindowEvent w)
{
System.exit(1);
}
}
public class WindowEventDemo
{
public static void main(String[] args)
{
new MyFrame("Window Event Demo");
}
}

Anonymous class
It is one type of inner class, but it has no name and it is defined wherever we want. An anonymous
inner class instantiated wherever it is being used. It is useful in Event Handling
import java.awt.*;
import java.awt.event.*;

class MyFrame extends Frame


{
public MyFrame(String title)
{
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(1);
}
}
);

setTitle(title);
setVisible(true);
setSize(400,400);
}
}

public class WindowEventDemo


{
public static void main(String[] args)
{
new MyFrame("Window Event Demo");
}
}
MouseEvent and MouseListener
A MouseEvent is fired to all its registered listeners, when you press, release, or click (press followed by release)
a mouse-button (left or right button) at the source object; or position the mouse-pointer at (enter) and away
(exit) from the source object.

A MouseEvent listener must implement the MouseListener interface, which declares the following
five abstract methods:

1. public void mouseClicked(MouseEvent e)


// Called-back when the mouse-button has been clicked (pressed followed by released) on the
source.
2. public void mousePressed(MouseEvent e)
3. public void mouseReleased(MouseEvent e)
// Called-back when a mouse-button has been pressed/released on the source.
// A mouse-click invokes mousePressed(), mouseReleased() and mouseClicked().
4. public void mouseEntered(MouseEvent e)
5. public void mouseExited(MouseEvent e)
// Called-back when the mouse-pointer has entered/exited the source.

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

class MyFrame extends Frame implements MouseListener


{
Label lblShowx, lblShowy;
TextField txtValuex, txtValuey;

public MyFrame(String title)


{
lblShowx = new Label("X Position :");
txtValuex = new TextField(20);

lblShowy = new Label("Y Position :");


txtValuey = new TextField(20);

setLayout(new FlowLayout(FlowLayout.LEFT));

add(lblShowx);
add(txtValuex);
add(lblShowy);
add(txtValuey);

addMouseListener(this);

setTitle(title);
setVisible(true);
setSize(400,400);
}

public void mouseClicked(MouseEvent e)


{
txtValuex.setText(e.getX() + "");
txtValuey.setText(e.getY() + "");
}

public void mousePressed(MouseEvent e){}


public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
}

public class WindowEventDemo


{
public static void main(String[] args)
{
new MyFrame("Window Event Demo");
}
}

MouseEvent and MouseMotionListener Interf


ace
A MouseEvent is also fired when you move and drag the mouse pointer at the source object. You need to
implement MouseMotionListener to handle the mouse-move and mouse-drag

The MouseMotionListener interface declares the following two abstract methods:

1. public void mouseDragged(MouseEvent e)


// Called-back when a mouse-button is pressed on the source component and then dragged

2. public void mouseMoved(MouseEvent e)


// Called-back when the mouse-pointer has been moved onto the source component but no
buttons have been pushed.

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

class MyFrame extends Frame implements MouseMotionListener


{
Label lblShowx, lblShowy;
TextField txtValuex, txtValuey;
public MyFrame(String title)
{
lblShowx = new Label("X Position :");
txtValuex = new TextField(20);

lblShowy = new Label("Y Position :");


txtValuey = new TextField(20);

setLayout(new FlowLayout(FlowLayout.LEFT));

add(lblShowx);
add(txtValuex);
add(lblShowy);
add(txtValuey);

addMouseMotionListener(this);

setTitle(title);
setVisible(true);
setSize(400,400);
}

public void mouseMoved(MouseEvent e)


{
txtValuex.setText(e.getX() + "");
txtValuey.setText(e.getY() + "");
}
public void mouseDragged(MouseEvent e){}
}

public class MouseEventDemo


{
public static void main(String[] args)
{
new MyFrame("Window Event Demo");
}
}

KeyEvent and KeyListener Interface


A KeyEvent is fired (to all its registered KeyListeners) when a key is pressed, released, and typed (pressed
followed by released) on the source object.

A KeyEvent must implement KeyListener interface, which declares three abstract methods:

public void keyTyped(KeyEvent e)

// Called-back when a key has been typed (pressed and released).


public void keyPressed(KeyEvent e)

public void keyReleased(KeyEvent e)

// Called-back when a key has been pressed/released.

he KeyEvent class inherits many useful methods from the InputEvent class, such as getModifiersEx, and a
couple of useful methods from the ComponentEvent and AWTEvent classes.

Method Purpose

int getKeyChar() Obtains the Unicode character associated with this event. Only rely on this value for key-typed
events.
int getKeyCode() Obtains the key code associated with this event. The key code identifies the particular key on the
keyboard that the user pressed or released. The KeyEvent class defines many key code constants
for commonly seen keys. For example, VK_A specifies the key labeled A, and VK_ESCAPE specifies
the Escape key.
String getKeyText(int) Return text descriptions of the event's key code and modifier keys, respectively.
String
getKeyModifiersText(i
nt)
int getModifiersEx() Return the extended modifiers mask for this event. There are methods inherited from
String the InputEvent class. Extended modifiers represent the state of all modal keys.
getModifiersExText(int The getModifiersExTextmethod returns a string describing the extended modifier keys and
modifiers) mouse buttons. Since the getModifiersEx and getModifiersExText methods provide more
information about key events, they are preferred over
the getKeyText or getKeyModifiersText methods.
boolean isActionKey() Returns true if the key firing the event is an action key. Examples of action keys include Cut,
Copy, Paste, Page Up, Caps Lock, the arrow and function keys. This information is valid only for
key-pressed and key-released events.
int getKeyLocation() Returns the location of the key that fired this event. This provides a way to distinguish keys that
occur more than once on a keyboard, such as the two shift keys, for example. The possible values
are KEY_LOCATION_STANDARD, KEY_LOCATION_LEFT, KEY_LOCATION_RIGHT, KEY_LOCATION_N
UMPAD, or KEY_LOCATION_UNKNOWN. This method always
returns KEY_LOCATION_UNKNOWNfor key-typed events.

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

// An AWT GUI program inherits from the top-level container java.awt.Frame


public class KeyEventDemo extends Frame implements KeyListener {
// This class acts as KeyEvent Listener

private TextField tfInput; // Single-line TextField to receive tfInput key


private TextArea taDisplay; // Multi-line TextArea to taDisplay result

// Constructor to setup the GUI components and event handlers


public KeyEventDemo() {
setLayout(new FlowLayout()); // "super" frame sets to FlowLayout
add(new Label("Enter Text: "));
tfInput = new TextField(10);
add(tfInput);
taDisplay = new TextArea(5, 40); // 5 rows, 40 columns
add(taDisplay);

tfInput.addKeyListener(this);
// tfInput TextField (source) fires KeyEvent.
// tfInput adds "this" object as a KeyEvent listener.

setTitle("KeyEvent Demo"); // "super" Frame sets title


setSize(400, 200); // "super" Frame sets initial size
setVisible(true); // "super" Frame shows
}

// The entry main() method


public static void main(String[] args) {
new KeyEventDemo(); // Let the constructor do the job
}

/** KeyEvent handlers */


// Called back when a key has been typed (pressed and released)
@Override
public void keyTyped(KeyEvent evt) {
taDisplay.append("You have typed " + evt.getKeyChar() + "\n");
}

// Not Used, but need to provide an empty body for compilation


@Override public void keyPressed(KeyEvent evt) { }
@Override public void keyReleased(KeyEvent evt) { }
}

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

public class AwtListenerDemo {


private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
private TextField textField;

public AwtListenerDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtListenerDemo awtListenerDemo = new AwtListenerDemo();
awtListenerDemo.showKeyListenerDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});

headerLabel = new Label();


headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showKeyListenerDemo(){


headerLabel.setText("Listener in action: KeyListener");

textField = new TextField(10);

textField.addKeyListener(new CustomKeyListener());
Button okButton = new Button("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusLabel.setText("Entered text: " + textField.getText());
}
});
controlPanel.add(textField);
controlPanel.add(okButton);
mainFrame.setVisible(true);
}

class CustomKeyListener implements KeyListener{


public void keyTyped(KeyEvent e) {
}

public void keyPressed(KeyEvent e) {


if(e.getKeyCode() == KeyEvent.VK_ENTER){
statusLabel.setText("Entered text: " + textField.getText());
}
}

public void keyReleased(KeyEvent e) {


}
}
}

Layout Managers and Panel


A container has a so-called layout manager to arrange its components. The layout managers provide a level of
abstraction to map your user interface on all windowing systems, so that the layout can be platform-
independent.

AWT provides the following layout managers (in package java.awt) : FlowLayout,
GridLayout, BorderLayout, GridBagLayout, BoxLayout, CardLayout, and others.

A container has a setLayout() method to set its layout manager:

public void setLayout(LayoutManager mgr)

To set up the layout of a Container (such as Frame, JFrame, Panel, or JPanel), you have to:
1. Construct an instance of the chosen layout object, via new and constructor, e.g., new FlowLayout())
2. Invoke the setLayout() method of the Container, with the layout object created as the argument;
3. Place the GUI components into the Container using the add() method in the correct order; or into
the correct zones.

For example,
// Allocate a Panel (container)

Panel p = new Panel();

// Allocate a new Layout object. The Panel container sets to this layout.

p.setLayout(new FlowLayout());

// The Panel container adds components in the proper order.

p.add(new JLabel("One"));

p.add(new JLabel("Two"));

p.add(new JLabel("Three"));

......

getLayout()
You can get the current layout via Container's getLayout().

Panel awtPanel = new Panel();

System.out.println(awtPanel.getLayout());

// java.awt.FlowLayout[hgap=5,vgap=5,align=center]

Panel's Initial Layout


Panel (and Swing's JPanel) provides a constructor to set its initial layout manager. It is because a primary
function of Panel is to layout a group of component in a particular layout.

public Panel (LayoutManager layout)

// Construct a Panel in the given layout, By default, Panel (and JPanel) has FlowLayout

// For example, create a Panel in BorderLayout

Panel mainPanel = new Panel(new BorderLayout());

FlowLayout
In the java.awt.FlowLayout, components are arranged from left-to-right inside the container in the
order that they are added (via container.add(aComponent)). When one row is filled, a new row will be
started. The actual appearance depends on the width of the display window.

Constructors
public FlowLayout();
public FlowLayout(int align);
public FlowLayout(int align, int hgap, int vgap);

align : FlowLayout.LEFT (or LEADING), FlowLayout.RIGHT (or TRAILING), or FlowLayout.CENTER


hgap, vgap : horizontal/vertical gap between the components

Note : By default, hgap=5, vgap=5, align=CENTER

Example
import java.awt.*;
import java.awt.event.*;

public class AWTFlowLayoutDemo extends Frame


{
private Button btn1, btn2, btn3, btn4, btn5, btn6;

/** Constructor to setup GUI components */


public AWTFlowLayoutDemo ()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
// "this" Frame sets layout to FlowLayout, which arranges the
components
// from left-to-right, and flow from top-to-bottom.

setFont(new Font("arial", 0, 30));


btn1 = new Button("Button 1");
add(btn1);
btn2 = new Button("This is Button 2");
add(btn2);
btn3 = new Button("3");
add(btn3);
btn4 = new Button("Another Button 4");
add(btn4);
btn5 = new Button("Button 5");
add(btn5);
btn6 = new Button("One More Button 6");
add(btn6);

setTitle("FlowLayout Demo");
setSize(1200,800);
setVisible(true);
}

public static void main(String[] args) {


new AWTFlowLayoutDemo();
}
}

GridLayout

In java.awt.GridLayout, components are arranged in a grid (matrix) of rows and columns inside
the Container. Components are added in a left-to-right, top-to-bottom manner in the order they are added
(via method aContainer.add(aComponent)).

Constructors
public GridLayout(int rows, int columns);
public GridLayout(int rows, int columns, int hgap, int vgap);
// By default: rows=1, cols=0, hgap=0, vgap=0
Example
import java.awt.*;
import java.awt.event.*;

public class AWTGridLayoutDemo extends Frame {


private Button btn1, btn2, btn3, btn4, btn5, btn6;

/** Constructor to setup GUI components */


public AWTGridLayoutDemo ()
{
setLayout(new GridLayout(3, 2, 30, 30));
// "this" Frame sets layout to 3x2 GridLayout, horizontal and
verical gaps of 3 pixels
// The components are added from left-to-right, top-to-bottom
btn1 = new Button("Button 1");
add(btn1);
btn2 = new Button("Button 2");
add(btn2);
btn3 = new Button("Button 3");
add(btn3);
btn4 = new Button("Button 4");
add(btn4);
btn5 = new Button("Button 5");
add(btn5);
btn6 = new Button("Button 6");
add(btn6);

setTitle("GridLayout Demo"); // "this" Frame sets title


setSize(600,400); // "this" Frame sets initial size
setVisible(true); // "this" Frame shows
}

/** The entry main() method */


public static void main(String[] args) {
new AWTGridLayoutDemo(); // Let the constructor do the job
}
}

If rows or cols is 0, but not both, then any number of components can be placed in that column or
row. If both the rows and cols are specified, the cols value is ignored. The actualcols is determined by
the actual number of components and rows.

BorderLayout
In java.awt.BorderLayout, the container is divided into 5 zones: EAST, WEST, SOUTH, NORTH, and CENTER.
Components are added using method aContainer.add(acomponent, aZone), where azone is
either BorderLayout.NORTH (or PAGE_START), BorderLayout.SOUTH (or PAGE_END),BorderLayout.WEST (or LI
NE_START), BorderLayout.EAST (or LINE_END), or BorderLayout.CENTER. The
method aContainer.add(aComponent)without specifying the zone adds the component to the CENTER.

You need not add components to all the 5 zones. The NORTH and SOUTH components may be stretched
horizontally; the EAST and WEST components may be stretched vertically; the CENTER component may
stretch both horizontally and vertically to fill any space left over.

Constructors
public BorderLayout();
public BorderLayout(int hgap, int vgap);
// By default hgap=0, vgap=0

Example
import java.awt.*;
import java.awt.event.*;

// An AWT GUI program inherits the top-level container java.awt.Frame


public class AWTBorderLayoutDemo extends Frame {
private Button btnNorth, btnSouth, btnCenter, btnEast, btnWest;

/** Constructor to setup GUI components */


public AWTBorderLayoutDemo () {
setLayout(new BorderLayout(3, 3));
// "this" Frame sets layout to BorderLayout,
// horizontal and vertical gaps of 3 pixels

// The components are added to the specified zone


btnNorth = new Button("NORTH");
add(btnNorth, BorderLayout.NORTH);
btnSouth = new Button("SOUTH");
add(btnSouth, BorderLayout.SOUTH);
btnCenter = new Button("CENTER");
add(btnCenter, BorderLayout.CENTER);
btnEast = new Button("EAST");
add(btnEast, BorderLayout.EAST);
btnWest = new Button("WEST");
add(btnWest, BorderLayout.WEST);

setTitle("BorderLayout Demo"); // "this" Frame sets title


setSize(280, 150); // "this" Frame sets initial size
setVisible(true); // "this" Frame shows
}

/** The entry main() method */


public static void main(String[] args) {
new AWTBorderLayoutDemo(); // Let the constructor do the job
}
}

Using Panels as Sub-Container to Organize


Components

An AWT Panel is a rectangular pane, which can be used as sub-container to organized a group of related
components in a specific layout (e.g.,FlowLayout, BorderLayout). Panels are secondary containers, which
shall be added into a top-level container (such as Frame), or another Panel.

For example, the following figure shows a Frame (in BorderLayout) containing
two Panels, panelResult in FlowLayout and panelButtons inGridLayout. panelResult is added to
the NORTH, and panelButtons is added to the CENTER.
import java.awt.*;
import java.awt.event.*;

// An AWT GUI program inherits the top-level container java.awt.Frame


public class AWTPanelDemo extends Frame {
private Button[] btnNumbers = new Button[10]; // Array of 10 numeric buttons
private Button btnHash, btnStar;
private TextField tfDisplay;

/** Constructor to setup GUI components */


public AWTPanelDemo () {
// Set up display panel
Panel panelDisplay = new Panel(new FlowLayout());
tfDisplay = new TextField("0", 20);
panelDisplay.add(tfDisplay);

// Set up button panel


Panel panelButtons = new Panel(new GridLayout(4, 3));
btnNumbers[1] = new Button("1");
panelButtons.add(btnNumbers[1]);
btnNumbers[2] = new Button("2");
panelButtons.add(btnNumbers[2]);
btnNumbers[3] = new Button("3");
panelButtons.add(btnNumbers[3]);
btnNumbers[4] = new Button("4");
panelButtons.add(btnNumbers[4]);
btnNumbers[5] = new Button("5");
panelButtons.add(btnNumbers[5]);
btnNumbers[6] = new Button("6");
panelButtons.add(btnNumbers[6]);
btnNumbers[7] = new Button("7");
panelButtons.add(btnNumbers[7]);
btnNumbers[8] = new Button("8");
panelButtons.add(btnNumbers[8]);
btnNumbers[9] = new Button("9");
panelButtons.add(btnNumbers[9]);
// Can use a loop for the above statements!
btnStar = new Button("*");
panelButtons.add(btnStar);
btnNumbers[0] = new Button("0");
panelButtons.add(btnNumbers[0]);
btnHash = new Button("#");
panelButtons.add(btnHash);

setLayout(new BorderLayout()); // "this" Frame sets to BorderLayout


add(panelDisplay, BorderLayout.NORTH);
add(panelButtons, BorderLayout.CENTER);

setTitle("BorderLayout Demo"); // "this" Frame sets title


setSize(200, 200); // "this" Frame sets initial size
setVisible(true); // "this" Frame shows
}

/** The entry main() method */


public static void main(String[] args) {
new AWTPanelDemo(); // Let the constructor do the job
}
}

BoxLayout

BoxLayout arrange components in a single row or column. It respects components' requests on the
minimum sizes.
AWT CheckBox
Checkbox control is used to turn an option on(true) or off(false). There is label for each checkbox representing
what the checkbox does. The state of a checkbox can be changed by clicking on it.

Constructors
S.N. Constructor & Description

1 Checkbox()
Creates a check box with an empty string for its label.
2 Checkbox(String label)
Creates a check box with the specified label.
3 Checkbox(String label, boolean state)
Creates a check box with the specified label and sets the specified state.
4 Checkbox(String label, boolean state, CheckboxGroup group)
Constructs a Checkbox with the specified label, set to the specified state, and in the specified check
box group.
5 Checkbox(String label, CheckboxGroup group, boolean state)
Creates a check box with the specified label, in the specified check box group, and set to the specified
state.

Class methods
S.N. Method & Description
1 void addItemListener(ItemListener l)
Adds the specified item listener to receive item events from this check box.
2 String getLabel()
Gets the label of this check box.
3 Object[] getSelectedObjects()
Returns an array (length 1) containing the checkbox label or null if the checkbox is not
selected.
4 boolean getState()
Determines whether this check box is in the on or off state.
5 void setLabel(String label)
Sets this check box's label to be the string argument.
6 void setState(boolean state)
Sets the state of this check box to the specified state.

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

public class AwtControlDemo {


private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtControlDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showCheckBoxDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showCheckBoxDemo(){

headerLabel.setText("Control in action: CheckBox");

Checkbox chkApple = new Checkbox("Apple");


Checkbox chkMango = new Checkbox("Mango");
Checkbox chkPeer = new Checkbox("Peer");

chkApple.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Apple Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});

chkMango.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Mango Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});

chkPeer.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Peer Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});

controlPanel.add(chkApple);
controlPanel.add(chkMango);
controlPanel.add(chkPeer);

mainFrame.setVisible(true);
}
}
AWT CheckBoxGroup
The CheckboxGroup class is used to group the set of checkbox.

constructors

CheckboxGroup() ()

Creates a new instance of CheckboxGroup.

Methods
S.N. Method & Description
1 Checkbox getCurrent()
Deprecated. As of JDK version 1.1, replaced by getSelectedCheckbox().
2 Checkbox getSelectedCheckbox()
Gets the current choice from this check box group.
3 void setCurrent(Checkbox box)
Deprecated. As of JDK version 1.1, replaced by setSelectedCheckbox(Checkbox).
4 void setSelectedCheckbox(Checkbox box)
Sets the currently selected check box in this group to be the specified check box.
5 String toString()
Returns a string representation of this check box group, including the value of its current
selection.

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

public class AwtControlDemo {

private Frame mainFrame;


private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showCheckBoxGroupDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showCheckBoxGroupDemo(){

headerLabel.setText("Control in action: CheckBoxGroup");

CheckboxGroup fruitGroup = new CheckboxGroup();

Checkbox chkApple = new Checkbox("Apple",fruitGroup,true);


Checkbox chkMango = new Checkbox("Mango",fruitGroup,false);
Checkbox chkPeer = new Checkbox("Peer",fruitGroup,false);

statusLabel.setText("Apple Checkbox: checked");


chkApple.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Apple Checkbox: checked");
}
});

chkMango.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Mango Checkbox: checked");
}
});

chkPeer.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Peer Checkbox: checked");
}
});

controlPanel.add(chkApple);
controlPanel.add(chkMango);
controlPanel.add(chkPeer);

mainFrame.setVisible(true);
}
}

AWT List
The List represents a list of text items. The list can be configured to that user can choose either one item or
multiple items.

constructors
S.N. Constructor & Description
1 List()
Creates a new scrolling list.
2 List(int rows)
Creates a new scrolling list initialized with the specified number of visible lines.
3 List(int rows, boolean multipleMode)
Creates a new scrolling list initialized to display the specified number of rows.
methods
S.N. Method & Description
1 void add(String item)
Adds the specified item to the end of scrolling list.
2 void add(String item, int index)
Adds the specified item to the the scrolling list at the position indicated by the index.
3 void addActionListener(ActionListener l)
Adds the specified action listener to receive action events from this list.
4 void addItem(String item)
Deprecated. replaced by add(String).
5 void addItem(String item, int index)
Deprecated. replaced by add(String, int).
6 void addItemListener(ItemListener l)
Adds the specified item listener to receive item events from this list.
9 void clear()
Deprecated. As of JDK version 1.1, replaced by removeAll().
10 int countItems()
Deprecated. As of JDK version 1.1, replaced by getItemCount().
11 void delItem(int position)
Deprecated. replaced by remove(String) and remove(int).
12 void delItems(int start, int end)
Deprecated. As of JDK version 1.1, Not for public use in the future. This method is
expected to be retained only as a package private method.
13 void deselect(int index)
Deselects the item at the specified index.
16 String getItem(int index)
Gets the item associated with the specified index.
17 int getItemCount()
Gets the number of items in the list.
19 String[] getItems()
Gets the items in the list.
24 int getRows()
Gets the number of visible lines in this list.
25 int getSelectedIndex()
Gets the index of the selected item on the list,
26 int[] getSelectedIndexes()
Gets the selected indexes on the list.
27 String getSelectedItem()
Gets the selected item on this scrolling list.
28 String[] getSelectedItems()
Gets the selected items on this scrolling list.
29 Object[] getSelectedObjects()
Gets the selected items on this scrolling list in an array of Objects.
33 boolean isSelected(int index)
Deprecated. As of JDK version 1.1, replaced by isIndexSelected(int).
43 void remove(int position)
Removes the item at the specified position from this scrolling list.
44 void remove(String item)
Removes the first occurrence of an item from the list.

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

public class AwtControlDemo {

private Frame mainFrame;


private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtControlDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showListDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showListDemo(){

headerLabel.setText("Control in action: List");


final List fruitList = new List(4,false);

fruitList.add("Apple");
fruitList.add("Grapes");
fruitList.add("Mango");
fruitList.add("Peer");

final List vegetableList = new List(4,true);

vegetableList.add("Lady Finger");
vegetableList.add("Onion");
vegetableList.add("Potato");
vegetableList.add("Tomato");

Button showButton = new Button("Show");

showButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {


String data = "Fruits Selected: "
+ fruitList.getItem(fruitList.getSelectedIndex());
data += ", Vegetables selected: ";
for(String vegetable:vegetableList.getSelectedItems()){
data += vegetable + " ";
}
statusLabel.setText(data);
}
});

controlPanel.add(fruitList);
controlPanel.add(vegetableList);
controlPanel.add(showButton);

mainFrame.setVisible(true);
}
}

AWT Choice
Choice control is used to show pop up menu of choices. Selected choice is shown on the top of the menu.

constructors
S.N. Constructor & Description
1 Choice() ()
Creates a new choice menu.

methods
S.N. Method & Description
1 void add(String item)
Adds an item to this Choice menu.
2 void addItem(String item)
Obsolete as of Java 2 platform v1.1.
3 void addItemListener(ItemListener l)
Adds the specified item listener to receive item events from this Choice menu.
7 String getItem(int index)
Gets the string at the specified index in this Choice menu.
8 int getItemCount()
Returns the number of items in this Choice menu.
11 int getSelectedIndex()
Returns the index of the currently selected item.
12 String getSelectedItem()
Gets a representation of the current choice as a string.
13 Object[] getSelectedObjects()
Returns an array (length 1) containing the currently selected item.
14 void insert(String item, int index)
Inserts the item into this choice at the specified position.
18 void remove(int position)
Removes an item from the choice menu at the specified position.
19 void remove(String item)
Removes the first occurrence of item from the Choice menu.
20 void removeAll()
Removes all items from the choice menu.
22 void select(int pos)
Sets the selected item in this Choice menu to be the item at the specified position.
23 void select(String str)
Sets the selected item in this Choice menu to be the item whose name is equal to the specified string.

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

public class AwtControlDemo {

private Frame mainFrame;


private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtControlDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showChoiceDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showChoiceDemo(){

headerLabel.setText("Control in action: Choice");


final Choice fruitChoice = new Choice();

fruitChoice.add("Apple");
fruitChoice.add("Grapes");
fruitChoice.add("Mango");
fruitChoice.add("Peer");

Button showButton = new Button("Show");

showButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Fruit Selected: "
+ fruitChoice.getItem(fruitChoice.getSelectedIndex());
statusLabel.setText(data);
}
});

controlPanel.add(fruitChoice);
controlPanel.add(showButton);

mainFrame.setVisible(true);
}
}

Swing
Introduction

Swing is part of the so-called "Java Foundation Classes (JFC)" (have you heard of MFC?), which was
introduced in 1997 after the release of JDK 1.1. JFC was subsequently included as an integral part of
JDK since JDK 1.2. JFC consists of:

• Swing API: for advanced graphical programming.


• Accessibility API: provides assistive technology for the disabled.

• Java 2D API: for high quality 2D graphics and images.

• Pluggable look and feel supports.

• Drag-and-drop support between Java and native applications.

The goal of Java GUI programming is to allow the programmer to build GUI that looks good on ALL
platforms. JDK 1.0's AWT was awkward and non-object-oriented (using manyevent.getSource()). JDK
1.1's AWT introduced event-delegation (event-driven) model, much clearer and object-oriented. JDK
1.1 also introduced inner class and JavaBeans – a component programming model for visual
programming environment (similar to Visual Basic and Dephi).

Swing appeared after JDK 1.1. It was introduced into JDK 1.1 as part of an add-on JFC (Java Foundation
Classes). Swing is a rich set of easy-to-use, easy-to-understand JavaBean GUI components that can be
dragged and dropped as "GUI builders" in visual programming environment. Swing is now an integral
part of Java since JDK 1.2.

10.2 Swing's Features

Swing is huge (consists of 18 API packages as in JDK 1.7) and has great depth. Compared with AWT,
Swing provides a huge and comprehensive collection of reusable GUI components, as shown in the
Figure below (extracted form Swing Tutorial).
The main features of Swing are (extracted from the Swing website):

1. Swing is written in pure Java (except a few classes) and therefore is 100% portable.

2. Swing components are lightweight. The AWT components are heavyweight (in terms of system
resource utilization). Each AWT component has its own opaque native display, and always
displays on top of the lightweight components. AWT components rely heavily on the underlying
windowing subsystem of the native operating system. For example, an AWT button ties to an
actual button in the underlying native windowing subsystem, and relies on the native windowing
subsystem for their rendering and processing. Swing components (JComponents) are written in
Java. They are generally not "weight-down" by complex GUI considerations imposed by the
underlying windowing subsystem.
3. Swing components support pluggable look-and-feel. You can choose between Java look-and-
feel and the look-and-feel of the underlying OS (e.g., Windows, UNIX or Mac). If the later is
chosen, a Swing button runs on the Windows looks like a Windows' button and feels like a
Window's button. Similarly, a Swing button runs on the UNIX looks like a UNIX's button and feels
like a UNIX's button.

4. Swing supports mouse-less operation, i.e., it can operate entirely using keyboard.

5. Swing components support "tool-tips".

6. Swing components are JavaBeans – a Component-based Model used in Visual Programming


(like Visual Basic). You can drag-and-drop a Swing component into a "design form" using a "GUI
builder" and double-click to attach an event handler.
7. Swing application uses AWT event-handling classes (in package java.awt.event). Swing added
some new classes in package javax.swing.event, but they are not frequently used.
8. Swing application uses AWT's layout manager (such as FlowLayout and BorderLayout in
package java.awt). It added new layout managers, such as Springs, Struts, andBoxLayout (in
package javax.swing).
9. Swing implements double-buffering and automatic repaint batching for smoother screen repaint.
10. Swing introduces JLayeredPane and JInternalFrame for creating Multiple Document Interface
(MDI) applications.
11. Swing supports floating toolbars (in JToolBar), splitter control, "undo".

12. Others - check the Swing website.

10.3 Using Swing API

If you understood the AWT programming (such as container/component, event-handling, layout


manager), switching over to Swing (or any other Graphics packages) is straight-forward.
Swing's Components

Compared with the AWT classes (in package java.awt), Swing component classes (in
package javax.swing) begin with a prefix "J", e.g., JButton, JTextField, JLabel, JPanel, JFrame,
or JApplet.
The above figure shows the class hierarchy of the swing GUI classes. Similar to AWT, there are two
groups of classes: containers and components. A container is used to hold components. A container
can also hold containers because it is a (subclass of) component.
As a rule, do not mix heavyweight AWT components and lightweight Swing components in the same
program, as the heavyweight components will always be painted on top of the lightweight
components.
Swing's Top-Level and Secondary Containers

Just like AWT application, a Swing application requires a top-level container. There are three top-level
containers in Swing:
1. JFrame: used for the application's main window (with an icon, a title, minimize/maximize/close
buttons, an optional menu-bar, and a content-pane), as illustrated.
2. JDialog: used for secondary pop-up window (with a title, a close button, and a content-pane).
3. JApplet: used for the applet's display-area (content-pane) inside a browser’s window.
Similarly to AWT, there are secondary containers (such as JPanel) which can be used to group and
layout relevant components.
The Content-Pane of Swing's Top-Level Container

However, unlike AWT, the JComponents shall not be added onto the top-level container
(e.g., JFrame, JApplet) directly because they are lightweight components. The JComponents must be
added onto the so-called content-paneof the top-level container. Content-pane is in fact
a java.awt.Container that can be used to group and layout components.

You could:

1. get the content-pane via getContentPane() from a top-level container, and add components
onto it. For example,
2. public class TestGetContentPane extends JFrame {
3. // Constructor
4. public TestGetContentPane() {
5. // Get the content-pane of this JFrame, which is a java.awt.Container
6. // All operations, such as setLayout() and add() operate on the content-pane
7. Container cp = this.getContentPane();
8. cp.setLayout(new FlowLayout());
9. cp.add(new JLabel("Hello, world!"));
10. cp.add(new JButton("Button"));
11. ......
12. }
13. .......

14. set the content-pane to a JPanel (the main panel created in your application which holds all
your GUI components) via JFrame's setContentPane().
15. public class TestSetContentPane extends JFrame {
16. // Constructor
17. public TestSetContentPane() {
18. // The "main" JPanel holds all the GUI components
19. JPanel mainPanel = new JPanel(new FlowLayout());
20. mainPanel.add(new JLabel("Hello, world!"));
21. mainPanel.add(new JButton("Button"));
22.
23. // Set the content-pane of this JFrame to the main JPanel
24. this.setContentPane(mainPanel);
25. ......
26. }
27. .......

Notes: If a component is added directly into a JFrame, it is added into the content-pane
of JFrame instead, i.e.,
// "this" is a JFrame
add(new JLabel("add to JFrame directly"));
// is executed as
getContentPane().add(new JLabel("add to JFrame directly"));

Event-Handling in Swing

Swing uses the AWT event-handling classes (in package java.awt.event). Swing introduces a few new
event-handling classes (in package javax.swing.event) but they are not frequently used.
Writing Swing Applications

In summary, to write a Swing application, you have:

1. Use the Swing components with prefix "J" in package javax.swing,


e.g., JFrame, JButton, JTextField, JLabel, etc.
2. A top-level container (such as JFrame or JApplet) is needed. The JComponents should be added
directly onto the top-level container. They shall be added onto the content-pane of the top-level
container. You can retrieve a reference to the content-pane by invoking
method getContentPane() from the top-level container, or set the content-pane to the
mainJPanel created in your program.
3. Swing applications uses AWT event-handling classes,
e.g., ActionEvent/ActionListener, MouseEvent/MouseListener, etc.

4. Run the constructor in the Event Dispatcher Thread (instead of Main thread) for thread safety, as
shown in the following program template.

10.4 Swing Program Template


1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4
5 // A Swing GUI application inherits from top-level container javax.swing.JFrame
6 public class ...... extends JFrame {
7
8 // private variables
9 // ......
10
11 /** Constructor to setup the GUI components */
12 public ......() {
13 Container cp = this.getContentPane();
14
15 // Content-pane sets layout
16 cp.setLayout(new ....Layout());
17
18 // Allocate the GUI components
19 // .....
20
21 // Content-pane adds components
22 cp.add(....);
23
24 // Source object adds listener
25 // .....
26
27 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
28 // Exit the program when the close-window button clicked
29 setTitle("......"); // "this" JFrame sets title
30 setSize(300, 150); // "this" JFrame sets initial size (or pack())
31 setVisible(true); // show it
32 }
33
34 /** The entry main() method */
35 public static void main(String[] args) {
36 // Run GUI codes in Event-Dispatching thread for thread-safety
37 SwingUtilities.invokeLater(new Runnable() {
38 @Override
39 public void run() {
40 new ......(); // Let the constructor do the job
41 }
42 });
43 }
44 }

I will explain this template in the following Swing example.

10.5 Swing Example 1: SwingCounter

Let's convert the earlier AWT application example into Swing. Compare the two source files and note
the changes (which are highlighted). The display is shown below. Note the differences in look and
feel between the AWT GUI components and Swing's.
1 import java.awt.*; // Using AWT containers and components
2 import java.awt.event.*; // Using AWT events and listener interfaces
3 import javax.swing.*; // Using Swing components and containers
4
5 // A Swing GUI application inherits from top-level container javax.swing.JFrame
6 public class SwingCounter extends JFrame {
7 private JTextField tfCount; // Use Swing's JTextField instead of AWT's TextFi
8 private int count = 0;
9
10 /** Constructor to setup the GUI */
11 public SwingCounter () {
12 // Retrieve the content-pane of the top-level container JFrame
13 // All operations done on the content-pane
14 Container cp = getContentPane();
15 cp.setLayout(new FlowLayout());
16
17 cp.add(new JLabel("Counter"));
18 tfCount = new JTextField("0", 10);
19 tfCount.setEditable(false);
20 cp.add(tfCount);
21
22 JButton btnCount = new JButton("Count");
23 cp.add(btnCount);
24
25 // Allocate an anonymous instance of an anonymous inner class that
26 // implements ActionListener as ActionEvent listener
27 btnCount.addActionListener(new ActionListener() {
28 @Override
29 public void actionPerformed(ActionEvent e) {
30 ++count;
31 tfCount.setText(count + "");
32 }
33 });
34
35 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit program if close-w
36 setTitle("Swing Counter"); // "this" JFrame sets title
37 setSize(300, 100); // "this" JFrame sets initial size
38 setVisible(true); // "this" JFrame shows
39 }
40
41 /** The entry main() method */
42 public static void main(String[] args) {
43 // Run the GUI construction in the Event-Dispatching thread for thread-safe
44 SwingUtilities.invokeLater(new Runnable() {
45 @Override
46 public void run() {
47 new SwingCounter(); // Let the constructor do the job
48 }
49 });
50 }
51 }

JFrame's Content-Pane

The JFrams's method getContentPane() returns the content-pane (which is a java.awt.Containter) of


the JFrame. You can then set its layout (the default layout is BorderLayout), and add components into
it. For example,
Container cp = getContentPane(); // Get the content-pane of this JFrame
cp.setLayout(new FlowLayout()); // content-pane sets to FlowLayout
cp.add(new JLabel("Counter")); // content-pane adds a JLabel component
......
cp.add(tfCount); // content-pane adds a JTextField component
......
cp.add(btnCount); // content-pane adds a JButton component
You can also use the JFrame's setContentPane() method to directly set the content-pane to
a JPanel (or a JComponent). For example,

JPanel displayPanel = new JPanel();


this.setContentPane(displayPanel);
// "this" JFrame sets its content-pane to a JPanel directly
.....

// The above is different from:


this.getContentPane().add(displayPanel);
// Add a JPanel into the content-pane. Appearance depends on the JFrame's layout.
JFrame's setDefaultCloseOperation()

Instead of writing a WindowEvent listener with a windowClosing() handler to process the "close-
window" button, JFrame provides a method called setDefaultCloseOperation() to sets the default
operation when the user initiates a "close" on this frame. Typically, we choose the
option JFrame.EXIT_ON_CLOSE, which terminates the application via a System.exit().

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Running the GUI Construction Codes on the Event-Dispatching Thread

In the previous examples, we invoke the constructor directly in the entry main() method to setup the
GUI components. For example,
// The entry main method
public static void main(String[] args) {
// Invoke the constructor (by allocating an instance) to setup the GUI
new SwingCounter();
}

The constructor will be executed in the so-called "Main-Program" thread. This may cause multi-
threading issues (such as unresponsive user-interface and deadlock).

It is recommended to execute the GUI setup codes in the so-called "Event-Dispatching" thread, instead
of "Main-Program" thread, for thread-safe operations. Event-dispatching thread, which processes
events, should be used when the codes updates the GUI.

To run the constructor on the event-dispatching thread,


invoke static method SwingUtilities.invokeLater() to asynchronously queue the constructor on
the event-dispatching thread. The codes will be run after all pending events have been processed. For
example,

public static void main(String[] args) {


// Run the GUI codes in the Event-dispatching thread for thread-safety
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new SwingCounter(); // Let the constructor do the job
}
});
}

Note: javax.swing.SwingUtilities.invokeLater() is a cover


for java.awt.EventQueue.invokeLater() (which is used in the NetBeans' Visual GUI Builder).
At times, for example in game programming, the constructor or the main() may contains non-GUI
codes. Hence, it is a common practice to create a dedicated method calledinitComponents() (used in
NetBeans visual GUI builder) or createAndShowGUI() (used in Swing tutorial) to handle all the GUI
codes (and another method called initGame() to handle initialization of the game's objects). This GUI
init method shall be run in the event-dispatching thread.
Warning Message "The serialization class does not declare a static final
serialVersionUID field of type long"

This warning message is triggered because java.awt.Frame (via its superclass java.awt.Component)
implements the java.io.Serializable interface. This interface enables the object to be written out to
an output stream serially (via method writeObject()); and read back into the program (via
method readObject()). The serialization runtime uses a number (calledserialVersionUID) to ensure
that the object read into the program is compatible with the class definition, and not belonging to
another version.

You have these options:

1. Simply ignore this warning message. If a serializable class does not explicitly declare
a serialVersionUID, then the serialization runtime will calculate a
defaultserialVersionUID value for that class based on various aspects of the class.
2. Add a serialVersionUID (Recommended), e.g.
private static final long serialVersionUID = 1L; // version 1
3. Suppress this particular warning via annotation @SuppressWarmomgs (in package java.lang) (JDK
1.5):
4. @SuppressWarnings("serial")

public class MyFrame extends JFrame { ...... }

10.6 Swing Example 2: SwingAccumulator


1 import java.awt.*; // Using AWT containers and components
2 import java.awt.event.*; // Using AWT events and listener interfaces
3 import javax.swing.*; // Using Swing components and containers
4
5 // A Swing GUI application inherits the top-level container javax.swing.JFrame
6 public class SwingAccumulator extends JFrame {
7 private JTextField tfInput, tfOutput;
8 private int numberIn; // input number
9 private int sum = 0; // accumulated sum, init to 0
10
11 /** Constructor to setup the GUI */
12 public SwingAccumulator() {
13 // Retrieve the content-pane of the top-level container JFrame
14 // All operations done on the content-pane
15 Container cp = getContentPane();
16 cp.setLayout(new GridLayout(2, 2, 5, 5));
17
18 add(new JLabel("Enter an Integer: "));
19 tfInput = new JTextField(10);
20 add(tfInput);
21 add(new JLabel("The Accumulated Sum is: "));
22 tfOutput = new JTextField(10);
23 tfOutput.setEditable(false); // read-only
24 add(tfOutput);
25
26 // Allocate an anonymous instance of an anonymous inner class that
27 // implements ActionListener as ActionEvent listener
28 tfInput.addActionListener(new ActionListener() {
29 @Override
30 public void actionPerformed(ActionEvent e) {
31 // Get the String entered into the input TextField, convert to int
32 numberIn = Integer.parseInt(tfInput.getText());
33 sum += numberIn; // accumulate numbers entered into sum
34 tfInput.setText(""); // clear input TextField
35 tfOutput.setText(sum + ""); // display sum on the output TextField
36 }
37 });
38
39 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit program if close-window
40 setTitle("Swing Accumulator"); // "this" Frame sets title
41 setSize(350, 120); // "this" Frame sets initial size
42 setVisible(true); // "this" Frame shows
43 }
44
45 /** The entry main() method */
46 public static void main(String[] args) {
47 // Run the GUI construction in the Event-Dispatching thread for thread-safety
48 SwingUtilities.invokeLater(new Runnable() {
49 @Override
50 public void run() {
51 new SwingAccumulator(); // Let the constructor do the job
52 }
53 });
54 }
55 }

11. Using Visual GUI Builder - NetBeans/Eclipse

If you have a complicated layout for your GUI application, you should use a GUI Builder, such as
NetBeans or Eclipse to layout your GUI components in a drag-and-drop manner, similar to the popular
visual languages such as Visual Basic and Dephi.
NetBeans
For using NetBeans GUI Builder, read my "Writing Java GUI (AWT/Swing) Application in NetBeans"; or
Swing Tutorial's "Learning Swing with the NetBeans IDE".
11.2 Eclipse
For using Eclipse GUI Builder, read "Writing Swing Applications using Eclipse GUI Builder".
Class java.awt.Checkbox
java.lang.Object
|
+----java.awt.Component
|
+----java.awt.Checkbox

public class Checkbox

extends Component

implements ItemSelectable

A check box is a graphical component that can be in either an "on" (true) or "off" (false)
state. Clicking on a check box changes its state from "on" to "off," or from "off" to "on.

Checkbox()

Creates a check box with no label.

Checkbox(String)

Creates a check box with the specified label.

Checkbox(String, boolean)

Creates a check box with the specified label.

Checkbox(String, boolean, CheckboxGroup)

Creates a check box with the specified label, in the specified check box group, and
set to the specified state.

Checkbox(String, CheckboxGroup, boolean)

Constructs a Checkbox with the specified label, set to the specified state, and in the
specified check box group.
Constructs a Checkbox with the specified label, set to the specified state, and in the
specified check box group.

addNotify
public void addNotify()
Creates the peer of the Checkbox. The peer allows you to change the look of the
Checkbox without changing its functionality.

Overrides:

addNotify in class Component

See Also:

createCheckbox, getToolkit

getLabel
public String getLabel()
Gets the label of this check box.

Returns:

the label of this check box, or null if this check box has no label.

See Also:

setLabel

setLabel
public synchronized void setLabel(String label)
Sets this check box's label to be the string argument.

Parameters:

label - a string to set as the new label, or null for no label.

See Also:

getLabel
getState
public boolean getState()
Determines whether this check box is in the "on" or "off" state. The boolean
value true indicates the "on" state, and false indicates the "off" state.

Returns:

the state of this check box, as a boolean value.

See Also:

setState

setState
public void setState(boolean state)
Sets the state of this check box to the specified state. The boolean
value true indicates the "on" state, and false indicates the "off" state.

Parameters:

state - the boolean state of the check box.

See Also:

getState

getSelectedObjects
public Object[] getSelectedObjects()
Returns the an array (length 1) containing the checkbox label or null if the checkbox
is not selected.

See Also:

ItemSelectable

getCheckboxGroup
public CheckboxGroup getCheckboxGroup()
Determines this check box's group.

Returns:
this check box's group, or null if the check box is not part of a check box group.

See Also:

setCheckboxGroup

setCheckboxGroup
public void setCheckboxGroup(CheckboxGroup g)
Sets this check box's group to be the specified check box group. If this check box is
already in a different check box group, it is first taken out of that group.

Parameters:

g - the new check box group, or null to remove this check box from any check box
group.

See Also:

getCheckboxGroup

addItemListener
public synchronized void addItemListener(ItemListener l)
Adds the specified item listener to receive item events from this check box.

Parameters:

l - the item listener.

See Also:

ItemEvent, ItemListener, removeItemListener

removeItemListener
public synchronized void removeItemListener(ItemListener l)
Removes the specified item listener so that the item listener no longer receives item
events from this check box.

Parameters:

l - the item listener.


See Also:

ItemEvent, ItemListener, addItemListener

processEvent
protected void processEvent(AWTEvent e)
Processes events on this check box. If the event is an instance of ItemEvent, this
method invokes the processItemEvent method. Otherwise, it calls its
superclass's processEvent method.

Parameters:

e - the event.

Overrides:

processEvent in class Component

See Also:

ItemEvent, processItemEvent

processItemEvent
protected void processItemEvent(ItemEvent e)
Processes item events occurring on this check box by dispatching them to any
registered ItemListener objects.

This method is not called unless item events are enabled for this component. Item
events are enabled when one of the following occurs:

• An ItemListener object is registered via addItemListener.


• Item events are enabled via enableEvents.

Parameters:

e - the item event.

See Also:

ItemEvent, ItemListener, addItemListener, enableEvents


paramString
protected String paramString()
Returns the parameter string representing the state of this check box. This string is
useful for debugging.

Returns:

the parameter string of this check box.

Overrides:

paramString in class Component


setLayout(new GridLayout(3, 1));
add(new Checkbox("one", null, true));
add(new Checkbox("two"));
add(new Checkbox("three"));

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

public class AwtControlDemo {

private Frame mainFrame;


private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtControlDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showCheckBoxDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showCheckBoxDemo(){

headerLabel.setText("Control in action: CheckBox");

Checkbox chkApple = new Checkbox("Apple");


Checkbox chkMango = new Checkbox("Mango");
Checkbox chkPeer = new Checkbox("Peer");

chkApple.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Apple Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});

chkMango.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Mango Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});

chkPeer.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Peer Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});

controlPanel.add(chkApple);
controlPanel.add(chkMango);
controlPanel.add(chkPeer);

mainFrame.setVisible(true);
}
}
Class java.awt.Checkbox
java.lang.Object
|
+----java.awt.Component
|
+----java.awt.Checkbox

public class Checkbox

extends Component

implements ItemSelectable

A check box is a graphical component that can be in either an "on" (true) or "off" (false)
state. Clicking on a check box changes its state from "on" to "off," or from "off" to "on."

The following code example creates a set of check boxes in a grid layout:

setLayout(new GridLayout(3, 1));


add(new Checkbox("one", null, true));
add(new Checkbox("two"));
add(new Checkbox("three"));

This image depicts the check boxes and grid layout created by this code example:

The button labeled one is in the "on" state, and the other two are in the "off" state. In this
example, which uses the GridLayout class, the states of the three check boxes are set
independently.

Alternatively, several check boxes can be grouped together under the control of a single
object, using the CheckboxGroup class. In a check box group, at most one button can be in the
"on" state at any given time. Clicking on a check box to turn it on forces any other check
box in the same group that is on into the "off" state.

See Also:
GridLayout, CheckboxGroup

Checkbox()

Creates a check box with no label.

Checkbox(String)

Creates a check box with the specified label.

Checkbox(String, boolean)

Creates a check box with the specified label.

Checkbox(String, boolean, CheckboxGroup)

Creates a check box with the specified label, in the specified check box group, and
set to the specified state.

Checkbox(String, CheckboxGroup, boolean)

Constructs a Checkbox with the specified label, set to the specified state, and in the
specified check box group.

addItemListener(ItemListener)

Adds the specified item listener to receive item events from this check box.

addNotify()

Creates the peer of the Checkbox.

getCheckboxGroup()

Determines this check box's group.

getLabel()
Gets the label of this check box.

getSelectedObjects()

Returns the an array (length 1) containing the checkbox label or null if the checkbox
is not selected.

getState()

Determines whether this check box is in the "on" or "off" state.

paramString()

Returns the parameter string representing the state of this check box.

processEvent(AWTEvent)

Processes events on this check box.

processItemEvent(ItemEvent)

Processes item events occurring on this check box by dispatching them to any
registered ItemListener objects.

removeItemListener(ItemListener)

Removes the specified item listener so that the item listener no longer receives item
events from this check box.

setCheckboxGroup(CheckboxGroup)

Sets this check box's group to be the specified check box group.

setLabel(String)

Sets this check box's label to be the string argument.

setState(boolean)

Sets the state of this check box to the specified state.


Checkbox
public Checkbox()
Creates a check box with no label. The state of this check box is set to "off," and it is
not part of any check box group.

Checkbox
public Checkbox(String label)
Creates a check box with the specified label. The state of this check box is set to
"off," and it is not part of any check box group.

Parameters:

label - a string label for this check box, or null for no label.

Checkbox
public Checkbox(String label,
boolean state)
Creates a check box with the specified label. The state of this check box is as
specified by the state argument, and it is not part of any check box group.

Parameters:

label - a string label for this check box, or null for no label.

state - the initial state of this check box.

Checkbox
public Checkbox(String label,
boolean state,
CheckboxGroup group)
Creates a check box with the specified label, in the specified check box group, and
set to the specified state.

Parameters:

label - a string label for this check box, or null for no label.

state - the initial state of this check box.


group - a check box group for this check box, or null for no group.

Checkbox
public Checkbox(String label,
CheckboxGroup group,
boolean state)
Constructs a Checkbox with the specified label, set to the specified state, and in the
specified check box group.

addNotify
public void addNotify()
Creates the peer of the Checkbox. The peer allows you to change the look of the
Checkbox without changing its functionality.

Overrides:

addNotify in class Component

See Also:

createCheckbox, getToolkit

getLabel
public String getLabel()
Gets the label of this check box.

Returns:

the label of this check box, or null if this check box has no label.

See Also:

setLabel

setLabel
public synchronized void setLabel(String label)
Sets this check box's label to be the string argument.

Parameters:
label - a string to set as the new label, or null for no label.

See Also:

getLabel

getState
public boolean getState()
Determines whether this check box is in the "on" or "off" state. The boolean
value true indicates the "on" state, and false indicates the "off" state.

Returns:

the state of this check box, as a boolean value.

See Also:

setState

setState
public void setState(boolean state)
Sets the state of this check box to the specified state. The boolean
value true indicates the "on" state, and false indicates the "off" state.

Parameters:

state - the boolean state of the check box.

See Also:

getState

getSelectedObjects
public Object[] getSelectedObjects()
Returns the an array (length 1) containing the checkbox label or null if the checkbox
is not selected.

See Also:

ItemSelectable
getCheckboxGroup
public CheckboxGroup getCheckboxGroup()
Determines this check box's group.

Returns:

this check box's group, or null if the check box is not part of a check box group.

See Also:

setCheckboxGroup

setCheckboxGroup
public void setCheckboxGroup(CheckboxGroup g)
Sets this check box's group to be the specified check box group. If this check box is
already in a different check box group, it is first taken out of that group.

Parameters:

g - the new check box group, or null to remove this check box from any check box
group.

See Also:

getCheckboxGroup

addItemListener
public synchronized void addItemListener(ItemListener l)
Adds the specified item listener to receive item events from this check box.

Parameters:

l - the item listener.

See Also:

ItemEvent, ItemListener, removeItemListener

removeItemListener
public synchronized void removeItemListener(ItemListener l)
Removes the specified item listener so that the item listener no longer receives item
events from this check box.

Parameters:

l - the item listener.

See Also:

ItemEvent, ItemListener, addItemListener

processEvent
protected void processEvent(AWTEvent e)
Processes events on this check box. If the event is an instance of ItemEvent, this
method invokes the processItemEvent method. Otherwise, it calls its
superclass's processEvent method.

Parameters:

e - the event.

Overrides:

processEvent in class Component

See Also:

ItemEvent, processItemEvent

processItemEvent
protected void processItemEvent(ItemEvent e)
Processes item events occurring on this check box by dispatching them to any
registered ItemListener objects.

This method is not called unless item events are enabled for this component. Item
events are enabled when one of the following occurs:

• An ItemListener object is registered via addItemListener.


• Item events are enabled via enableEvents.

Parameters:
e - the item event.

See Also:

ItemEvent, ItemListener, addItemListener, enableEvents

paramString
protected String paramString()
Returns the parameter string representing the state of this check box. This string is
useful for debugging.

Returns:

the parameter string of this check box.

Overrides:

paramString in class Component

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

public class AwtControlDemo {

private Frame mainFrame;


private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtControlDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showCheckBoxGroupDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
controlPanel = new Panel();
controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showCheckBoxGroupDemo(){

headerLabel.setText("Control in action: CheckBoxGroup");

CheckboxGroup fruitGroup = new CheckboxGroup();

Checkbox chkApple = new Checkbox("Apple",fruitGroup,true);


Checkbox chkMango = new Checkbox("Mango",fruitGroup,false);
Checkbox chkPeer = new Checkbox("Peer",fruitGroup,false);

statusLabel.setText("Apple Checkbox: checked");


chkApple.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Apple Checkbox: checked");
}
});

chkMango.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Mango Checkbox: checked");
}
});

chkPeer.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
statusLabel.setText("Peer Checkbox: checked");
}
});

controlPanel.add(chkApple);
controlPanel.add(chkMango);
controlPanel.add(chkPeer);

mainFrame.setVisible(true);
}
}
Class java.awt.Choice

Choice control is used to show pop up menu of choices. Selected choice is shown on the top of the
menu.

Class declaration
Following is the declaration for java.awt.Choice class:
public class Choice
extends Component
implements ItemSelectable, Accessible

Class constructors
S.N. Constructor & Description

Choice() ()
1
Creates a new choice menu.

Class methods
S.N. Method & Description

void add(String item)


1
Adds an item to this Choice menu.

void addItem(String item)


2
Obsolete as of Java 2 platform v1.1.

void addItemListener(ItemListener l)
3 Adds the specified item listener to receive item events from this Choice
menu.

void addNotify()
4
Creates the Choice's peer.

int countItems()
5
Deprecated. As of JDK version 1.1, replaced by getItemCount().

AccessibleContext getAccessibleContext()
6
Gets the AccessibleContext associated with this Choice.

String getItem(int index)


7
Gets the string at the specified index in this Choice menu.
int getItemCount()
8
Returns the number of items in this Choice menu.

ItemListener[] getItemListeners()
9
Returns an array of all the item listeners registered on this choice.

<T extends EventListener> T[] getListeners(Class<T> listenerType)


10 Returns an array of all the objects currently registered as FooListeners upon
this Choice.

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

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

Object[] getSelectedObjects()
13
Returns an array (length 1) containing the currently selected item.

void insert(String item, int index)


14
Inserts the item into this choice at the specified position.

protected String paramString()


15
Returns a string representing the state of this Choice menu.

protected void processEvent(AWTEvent e)


16
Processes events on this choice.

protected void processItemEvent(ItemEvent e)


17 Processes item events occurring on this Choice menu by dispatching them to
any registered ItemListener objects.

void remove(int position)


18
Removes an item from the choice menu at the specified position.

void remove(String item)


19
Removes the first occurrence of item from the Choice menu.

void removeAll()
20
Removes all items from the choice menu.

void removeItemListener(ItemListener l)
21 Removes the specified item listener so that it no longer receives item events
from this Choice menu.
void select(int pos)
22 Sets the selected item in this Choice menu to be the item at the specified
position.

void select(String str)


23 Sets the selected item in this Choice menu to be the item whose name is
equal to the specified string.

Methods inherited
This class inherits methods from the following classes:

• java.awt.Component

• java.lang.Object

Choice Example
Create the following java program using any editor of your choice in say D:/ > AWT > com >
tutorialspoint > gui >
AwtControlDemo.java

package com.tutorialspoint.gui;

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

public class AwtControlDemo {

private Frame mainFrame;


private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtControlDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showChoiceDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showChoiceDemo(){

headerLabel.setText("Control in action: Choice");


final Choice fruitChoice = new Choice();

fruitChoice.add("Apple");
fruitChoice.add("Grapes");
fruitChoice.add("Mango");
fruitChoice.add("Peer");

Button showButton = new Button("Show");

showButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Fruit Selected: "
+ fruitChoice.getItem(fruitChoice.getSelectedIndex());
statusLabel.setText(data);
}
});

controlPanel.add(fruitChoice);
controlPanel.add(showButton);

mainFrame.setVisible(true);
}
}

AWT List Class


Introduction
The List represents a list of text items. The list can be configured to that user can choose either one
item or multiple items.

Class declaration
Following is the declaration for java.awt.List class:
public class List
extends Component
implements ItemSelectable, Accessible

Class constructors
S.N. Constructor & Description
List()
1
Creates a new scrolling list.

List(int rows)
2 Creates a new scrolling list initialized with the specified number of visible
lines.

List(int rows, boolean multipleMode)


3
Creates a new scrolling list initialized to display the specified number of rows.

Class methods
<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this List.

S.N. Method & Description

void add(String item)


1
Adds the specified item to the end of scrolling list.

void add(String item, int index)


2 Adds the specified item to the the scrolling list at the position indicated by
the index.

void addActionListener(ActionListener l)
3
Adds the specified action listener to receive action events from this list.

void addItem(String item)


4
Deprecated. replaced by add(String).

void addItem(String item, int index)


5
Deprecated. replaced by add(String, int).

void addItemListener(ItemListener l)
6
Adds the specified item listener to receive item events from this list.

void addNotify()
7
Creates the peer for the list.

boolean allowsMultipleSelections()
8
Deprecated. As of JDK version 1.1, replaced by isMultipleMode().

void clear()
9
Deprecated. As of JDK version 1.1, replaced by removeAll().
int countItems()
10
Deprecated. As of JDK version 1.1, replaced by getItemCount().

void delItem(int position)


11
Deprecated. replaced by remove(String) and remove(int).

void delItems(int start, int end)


12 Deprecated. As of JDK version 1.1, Not for public use in the future. This
method is expected to be retained only as a package private method.

void deselect(int index)


13
Deselects the item at the specified index.

AccessibleContext getAccessibleContext()
14
Gets the AccessibleContext associated with this List.

ActionListener[] getActionListeners()
15
Returns an array of all the action listeners registered on this list.

String getItem(int index)


16
Gets the item associated with the specified index.

int getItemCount()
17
Gets the number of items in the list.

ItemListener[] getItemListeners()
18
Returns an array of all the item listeners registered on this list.

String[] getItems()
19
Gets the items in the list.

Dimension getMinimumSize()
20
Determines the minimum size of this scrolling list.

Dimension getMinimumSize(int rows)


21
Gets the minumum dimensions for a list with the specified number of rows.

Dimension getPreferredSize()
22
Gets the preferred size of this scrolling list.

Dimension getPreferredSize(int rows)


23
Gets the preferred dimensions for a list with the specified number of rows.
int getRows()
24
Gets the number of visible lines in this list.

int getSelectedIndex()
25
Gets the index of the selected item on the list,

int[] getSelectedIndexes()
26
Gets the selected indexes on the list.

String getSelectedItem()
27
Gets the selected item on this scrolling list.

String[] getSelectedItems()
28
Gets the selected items on this scrolling list.

Object[] getSelectedObjects()
29
Gets the selected items on this scrolling list in an array of Objects.

int getVisibleIndex()
30 Gets the index of the item that was last made visible by the method
makeVisible.

boolean isIndexSelected(int index)


31
Determines if the specified item in this scrolling list is selected.

boolean isMultipleMode()
32
Determines whether this list allows multiple selections.

boolean isSelected(int index)


33
Deprecated. As of JDK version 1.1, replaced by isIndexSelected(int).

void makeVisible(int index)


34
Makes the item at the specified index visible.

Dimension minimumSize()
35
Deprecated. As of JDK version 1.1, replaced by getMinimumSize().

Dimension minimumSize(int rows)


36
Deprecated. As of JDK version 1.1, replaced by getMinimumSize(int).

protected String paramString()


37
Returns the parameter string representing the state of this scrolling list.
Dimension preferredSize()
38
Deprecated. As of JDK version 1.1, replaced by getPreferredSize().

Dimension preferredSize(int rows)


39
Deprecated. As of JDK version 1.1, replaced by getPreferredSize(int).

protected void processActionEvent(ActionEvent e)


40 Processes action events occurring on this component by dispatching them to
any registered ActionListener objects.

protected void processEvent(AWTEvent e)


41
Processes events on this scrolling list.

protected void processItemEvent(ItemEvent e)


42 Processes item events occurring on this list by dispatching them to any
registered ItemListener objects.

void remove(int position)


43
Removes the item at the specified position from this scrolling list.

void remove(String item)


44
Removes the first occurrence of an item from the list.

void removeActionListener(ActionListener l)
45 Removes the specified action listener so that it no longer receives action
events from this list.

void removeAll()
46
Removes all items from this list.

void removeItemListener(ItemListener l)
47 Removes the specified item listener so that it no longer receives item events
from this list.

void removeNotify()
48
Removes the peer for this list.

void replaceItem(String newValue, int index)


49 Replaces the item at the specified index in the scrolling list with the new
string.

void select(int index)


50
Selects the item at the specified index in the scrolling list.
void setMultipleMode(boolean b)
51
Sets the flag that determines whether this list allows multiple selections.

void setMultipleSelections(boolean b)
52
Deprecated. As of JDK version 1.1, replaced by setMultipleMode(boolean).

Methods inherited
This class inherits methods from the following classes:

• java.awt.Component

• java.lang.Object

List Example
Create the following java program using any editor of your choice in say D:/ > AWT > com >
tutorialspoint > gui >
AwtControlDemo.java

package com.tutorialspoint.gui;

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

public class AwtControlDemo {

private Frame mainFrame;


private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtControlDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showListDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showListDemo(){

headerLabel.setText("Control in action: List");


final List fruitList = new List(4,false);

fruitList.add("Apple");
fruitList.add("Grapes");
fruitList.add("Mango");
fruitList.add("Peer");

final List vegetableList = new List(4,true);

vegetableList.add("Lady Finger");
vegetableList.add("Onion");
vegetableList.add("Potato");
vegetableList.add("Tomato");

Button showButton = new Button("Show");

showButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {


String data = "Fruits Selected: "
+ fruitList.getItem(fruitList.getSelectedIndex());
data += ", Vegetables selected: ";
for(String vegetable:vegetableList.getSelectedItems()){
data += vegetable + " ";
}
statusLabel.setText(data);
}
});

controlPanel.add(fruitList);
controlPanel.add(vegetableList);
controlPanel.add(showButton);

mainFrame.setVisible(true);
}
}

AWT Image Class

Introduction
Image control is superclass for all image classes representing graphical images.
Class declaration
Following is the declaration for java.awt.Image class:
public abstract class Image
extends Object

Field
Following are the fields for java.awt.Image class:
• protected float accelerationPriority -- Priority for accelerating this image.
• static int SCALE_AREA_AVERAGING -- Use the Area Averaging image scaling algorithm.
• static int SCALE_DEFAULT -- Use the default image-scaling algorithm.
• static int SCALE_FAST -- Choose an image-scaling algorithm that gives higher priority to scaling speed
than smoothness of the scaled image.
• static int SCALE_REPLICATE -- Use the image scaling algorithm embodied in the ReplicateScaleFilter
class.
• static int SCALE_SMOOTH -- Choose an image-scaling algorithm that gives higher priority to image
smoothness than scaling speed.
• static Object UndefinedProperty -- The UndefinedProperty object should be returned whenever a property
which was not defined for a particular image is fetched.

Class constructors
S.N. Constructor & Description

1 Image()

Class methods
S.N. Method & Description

void flush()
1
Flushes all reconstructable resources being used by this Image object.

float getAccelerationPriority()
2
Returns the current value of the acceleration priority hint.

ImageCapabilities getCapabilities(GraphicsConfiguration gc)


3 Returns an ImageCapabilities object which can be inquired as to the
capabilities of this Image on the specified GraphicsConfiguration.

abstract Graphics getGraphics()


4
Creates a graphics context for drawing to an off-screen image.

abstract int getHeight(ImageObserver observer)


5
Determines the height of the image.
abstract Object getProperty(String name, ImageObserver observer)
6
Gets a property of this image by name.

Image getScaledInstance(int width, int height, int hints)


7
Creates a scaled version of this image.

abstract ImageProducer getSource()


8
Gets the object that produces the pixels for the image.

abstract int getWidth(ImageObserver observer)


9
Determines the width of the image.

void setAccelerationPriority(float priority)


10
Sets a hint for this image about how important acceleration is.

Methods inherited
This class inherits methods from the following classes:

• java.lang.Object

Image Example
Create the following java program using any editor of your choice in say D:/ > AWT > com >
tutorialspoint > gui >
AwtControlDemo.java

package com.tutorialspoint.gui;

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

public class AwtControlDemo {

private Frame mainFrame;


private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;

public AwtControlDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showImageDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

private void showImageDemo(){


headerLabel.setText("Control in action: Image");

controlPanel.add(new ImageComponent("resources/java.jpg"));
mainFrame.setVisible(true);
}

class ImageComponent extends Component {

BufferedImage img;

public void paint(Graphics g) {


g.drawImage(img, 0, 0, null);
}

public ImageComponent(String path) {


try {
img = ImageIO.read(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
}

public Dimension getPreferredSize() {


if (img == null) {
return new Dimension(100,100);
} else {
return new Dimension(img.getWidth(), img.getHeight());
}
}
}
}
Compile the program using command prompt. Go to D:/ > AWT and type the following command.
D:\AWT>javac com\tutorialspoint\gui\AwtControlDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtControlDemo

Verify the following output

You might also like