Java AWT and Swing
Java AWT and Swing
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.
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.
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,
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:
// Other methods
......
......
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.
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.
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();
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.
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
Program LabelDemo
import java.awt.*;
public MyFrame1()
{
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);
}
}
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 Methods
public String getText();
// Get the current text on this TextField instance
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
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
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.*;
public MyFrame()
{
panel1 = new Panel();
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();
}
}
public MyFrame()
{
panel1 = new Panel();
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);
}
switch(str)
{
case "Addition":
ans = n1+n2;
break;
case "Subtraction":
ans = n1-n2;
break;
default:
break;
}
txt3.setText(ans+"");
} -----
}
}
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.
Clicking a Button (or hitting the "Enter" key on a TextField) fires an ActionEvent to all
its ActionEvent listener(s).
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.
import java.awt.*;
import java.awt.event.*;
setLayout(new FlowLayout(FlowLayout.RIGHT));
add(btnExit);
addWindowListener(this);
btnExit.addActionListener(this);
setTitle(title);
setVisible(true);
setSize(400,400);
}
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
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.
setLayout(new FlowLayout(FlowLayout.RIGHT));
add(btnExit);
addWindowListener(new MyWindow());
btnExit.addActionListener(this);
setTitle(title);
setVisible(true);
setSize(400,400);
}
import java.awt.*;
import java.awt.event.*;
setLayout(new FlowLayout(FlowLayout.RIGHT));
add(btnExit);
addWindowListener(new MyWindow(this));
btnExit.addActionListener(this);
setTitle(title);
setVisible(true);
setSize(400,400);
}
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.*;
setTitle(title);
setVisible(true);
setSize(400,400);
}
}
A MouseEvent listener must implement the MouseListener interface, which declares the following
five abstract methods:
import java.awt.*;
import java.awt.event.*;
setLayout(new FlowLayout(FlowLayout.LEFT));
add(lblShowx);
add(txtValuex);
add(lblShowy);
add(txtValuey);
addMouseListener(this);
setTitle(title);
setVisible(true);
setSize(400,400);
}
import java.awt.*;
import java.awt.event.*;
setLayout(new FlowLayout(FlowLayout.LEFT));
add(lblShowx);
add(txtValuex);
add(lblShowy);
add(txtValuey);
addMouseMotionListener(this);
setTitle(title);
setVisible(true);
setSize(400,400);
}
A KeyEvent must implement KeyListener interface, which declares three abstract methods:
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.*;
tfInput.addKeyListener(this);
// tfInput TextField (source) fires KeyEvent.
// tfInput adds "this" object as a KeyEvent listener.
import java.awt.*;
import java.awt.event.*;
public AwtListenerDemo(){
prepareGUI();
}
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
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);
}
AWT provides the following layout managers (in package java.awt) : FlowLayout,
GridLayout, BorderLayout, GridBagLayout, BoxLayout, CardLayout, and others.
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)
// Allocate a new Layout object. The Panel container sets to this layout.
p.setLayout(new FlowLayout());
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().
System.out.println(awtPanel.getLayout());
// java.awt.FlowLayout[hgap=5,vgap=5,align=center]
// Construct a Panel in the given layout, By default, Panel (and JPanel) has FlowLayout
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);
Example
import java.awt.*;
import java.awt.event.*;
setTitle("FlowLayout Demo");
setSize(1200,800);
setVisible(true);
}
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.*;
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 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.*;
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 AwtControlDemo(){
prepareGUI();
}
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
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() ()
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 AwtControlDemo(){
prepareGUI();
}
public static void main(String[] args){
AwtControlDemo awtControlDemo = new AwtControlDemo();
awtControlDemo.showCheckBoxGroupDemo();
}
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
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 AwtControlDemo(){
prepareGUI();
}
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
fruitList.add("Apple");
fruitList.add("Grapes");
fruitList.add("Mango");
fruitList.add("Peer");
vegetableList.add("Lady Finger");
vegetableList.add("Onion");
vegetableList.add("Potato");
vegetableList.add("Tomato");
showButton.addActionListener(new ActionListener() {
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 AwtControlDemo(){
prepareGUI();
}
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
fruitChoice.add("Apple");
fruitChoice.add("Grapes");
fruitChoice.add("Mango");
fruitChoice.add("Peer");
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:
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.
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.
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
4. Run the constructor in the Event Dispatcher Thread (instead of Main thread) for thread safety, as
shown in the following program template.
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
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);
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.
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.
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")
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
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()
Checkbox(String)
Checkbox(String, boolean)
Creates a check box with the specified label, in the specified check box group, and
set to the specified state.
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:
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:
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:
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:
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:
See Also:
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:
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:
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:
Parameters:
See Also:
Returns:
Overrides:
import java.awt.*;
import java.awt.event.*;
public AwtControlDemo(){
prepareGUI();
}
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
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:
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()
Checkbox(String)
Checkbox(String, boolean)
Creates a check box with the specified label, in the specified check box group, and
set to the specified state.
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()
getCheckboxGroup()
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()
paramString()
Returns the parameter string representing the state of this check box.
processEvent(AWTEvent)
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)
setState(boolean)
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.
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.
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:
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:
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:
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:
See Also:
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:
See Also:
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:
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:
Parameters:
e - the item event.
See Also:
paramString
protected String paramString()
Returns the parameter string representing the state of this check box. This string is
useful for debugging.
Returns:
Overrides:
import java.awt.*;
import java.awt.event.*;
public AwtControlDemo(){
prepareGUI();
}
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
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 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.
ItemListener[] getItemListeners()
9
Returns an array of all the item listeners registered on 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 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.
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 AwtControlDemo(){
prepareGUI();
}
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
fruitChoice.add("Apple");
fruitChoice.add("Grapes");
fruitChoice.add("Mango");
fruitChoice.add("Peer");
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);
}
}
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.
Class methods
<T extends EventListener> T[] getListeners(Class<T> listenerType)
Returns an array of all the objects currently registered as FooListeners upon this List.
void addActionListener(ActionListener l)
3
Adds the specified action listener to receive action events from this list.
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().
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.
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 getPreferredSize()
22
Gets the preferred size of this scrolling 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 isMultipleMode()
32
Determines whether this list allows multiple selections.
Dimension minimumSize()
35
Deprecated. As of JDK version 1.1, replaced by getMinimumSize().
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 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 AwtControlDemo(){
prepareGUI();
}
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
fruitList.add("Apple");
fruitList.add("Grapes");
fruitList.add("Mango");
fruitList.add("Peer");
vegetableList.add("Lady Finger");
vegetableList.add("Onion");
vegetableList.add("Potato");
vegetableList.add("Tomato");
showButton.addActionListener(new ActionListener() {
controlPanel.add(fruitList);
controlPanel.add(vegetableList);
controlPanel.add(showButton);
mainFrame.setVisible(true);
}
}
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.
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 AwtControlDemo(){
prepareGUI();
}
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
controlPanel.add(new ImageComponent("resources/java.jpg"));
mainFrame.setVisible(true);
}
BufferedImage img;
If no error comes that means compilation is successful. Run the program using following command.
D:\AWT>java com.tutorialspoint.gui.AwtControlDemo