Professional Documents
Culture Documents
12 Graphical User Interface
12 Graphical User Interface
XII. Graphical User Interface
Objectives
In this chapter, a brief overview of the Swing class and GUI’s used in Java is discussed.
To understand the design principles of graphical user interfaces.
To be able to build graphical user interfaces.
To understand the packages containing graphical user interface components and event
handling classes and interfaces.
To be able to create and manipulate buttons, labels, lists, text fields and panels.
To understand mouse and keyboard events.
To understand and be able to use layout managers.
Introduction
A graphical user interface (GUI) presents a pictorial interface to a program. A GUI gives a
program a distinctive “look” and “feel”. GUI’s are built from GUI components (sometimes called
controls or widgets – shorthand notation for window gadgets). A GUI component is an object
with which the user interacts via the mouse or the keyboard.
Common GUI components:
Component Description
JLabel An area where uneditable text or icons can be displayed.
An area in which the user inputs data from the keyboard. The area
JTextField
can also display information.
JButton An area that triggers an event when called.
JCheckBox A GUI component that is either selected or not selected.
A drop‐down list of items from which the user can make a
JComboBox selection by clicking an item in the list or by typing into the box, if
permitted.
An area where a list of items is displayed from which the user can
make a selection by clicking once on any element on the list.
JList
Double‐clicking an element in the list generates an action event.
Multiple elements can be selected.
JPanel A container in which components can be placed.
Table 10.1: Common Swing Components Classes
Training‐workshop on Object‐oriented Programming using Java
83 | P a g e
Swing Overview
The classes that are used to create GUI components mentioned above are part of the
Swing GUI components from package javax.swing. These are the newest GUI components of
the Java 2 platform. Swing components are written, manipulated and displayed completely in
Java (so‐called Java components).
The original GUI components from the Abstract Windowing Toolkit package java.awt
(also called the AWT) are tied directly to the local platform’s graphical user interface
capabilities. So, a Java program executing on different Java platforms has a different
appearance and sometimes even different user interactions on each platform. The swing
components allow the programmer to specify a different look and feel for each platform, or a
uniform look and feel across all platforms, or even to change the look‐and‐feel while the
program is running.
Java.lang.Object
Java.awt.Component
Java.awt.Container
Java.swing.JComponent
Figure 10.1: Common Swing Components Classes
The figure above shows an inheritance hierarchy of the classes that define attributes
and behaviours that are common to most Swing components. Each class is displayed with its
fully qualified package name and a class name. Much of each GUI component’s functionality is
derived from these classes. A class that inherits from the Component class is a component.
Class Component defines the methods that can be applied to an object of any subclass
of Component.
A Container is a collection of related components. In applications with JFrame and in
applets, we attach components to the content pane – a Container. Class Container defines the
set of methods that can be applied to an object of any subclass of Container.
Training‐workshop on Object‐oriented Programming using Java
84 | P a g e
Figure 10.2: An Example of a Java Container ‐ Frame
Class JComponent is the superclass to most Swing components. This class defines the
set of methods that can be applied to an object of any subclass of JComponent.
Swing Component Features
Swing components that subclass JComponent have many features, including:
1. A pluggable look and feel that can be used to customize the look and feel when
the program executes on different platforms.
2. Shortcut keys called mnemonics for direct access to GUI components through
the keyboard.
3. Common event handling capabilities for cases where several GUI components
initiate the same actions in a program.
4. Brief descriptions of a GUI component’s purpose (called tool tips) that are
displayed when the mouse cursor is positioned over the component for a short
time.
5. Support for assistive technologies such as braile screen readers for blind people.
6. Support for user interface localization – customizing the user interface for
display in different languages and cultural conventions.
JLabel
Labels display fixed text or images on a GUI as information to the user, for example, as a
label in front of a JTextField, etc. You can have text, an image, or both on a JLabel. A JLabel has
a transparent background, so it will always match the container it is in.
Assume the following declarations.
String text;
Icon image;
int alignment; // JLabel.LEFT, JLabel.Center, or JLabel.RIGHT.
JLabel yourLabel = new JLabel(text);
JLabel yourLabel = new JLabel(text, alignment);
JLabel yourLabel = new JLabel(image);
Training‐workshop on Object‐oriented Programming using Java
85 | P a g e
Figure 10.3: Uses of JLabels (Image and Text)
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
SystemJava()
{
setTitle("Java Example");
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(lbl1);
c.add(lbl2);
c.add(lbl3);
setSize(200,300);
setVisible(true);
}
{
SystemJava app = new SystemJava();
Figure 10.1 shows 3 JLabels: a label with text only, a label with an icon, and a label
with both text and icon. The first JLabel lbl1 is initialized with a pre‐defined text, lbl2 displays an
icon which is created through the method ImageIcon, and lbl3 uses both pre‐defined text and
the icon. All three JLabels, after having been initialized, are set up to have tool tip text on them
using the setToolTipText method and then finally added to the container.
JTextField and JPasswordField
A text field is a basic text control that enables the user to type a small amount of text.
When the user indicates that text entry is complete (usually by pressing Enter), the text field
fires an action event.
The JPasswordField class, a subclass of JTextField, provides specialized text fields for
password entry. For security reasons, a password field does not show the characters that the
user types. Instead, the field displays a character different from the one typed, such as an
asterisk '*'. As another security precaution, a password field stores its value as an array of
characters, rather than as a string. Like an ordinary text field, a password field fires an action
event when the user indicates that text entry is complete, for example by pressing the Enter
button.
Constructors:
JTextField tf = new JTextField(int columns);
The number of columns is approximate because the width of text depends on the font
and width of individual characters.
JTextField tf = new JTextField(String initial);
This puts the initial String in the JTextField. The size of the JTextField is set from this
String.
Training‐workshop on Object‐oriented Programming using Java
87 | P a g e
This creates a JTextField columns wide with value initial.
Example:
Figure 10.4: JTextField and JPasswordField
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
SystemJava()
{
setTitle("Java Example");
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(txt1);
c.add(txt2);
c.add(txt3);
Training‐workshop on Object‐oriented Programming using Java
88 | P a g e
c.add(pwd);
setSize(300,300);
setVisible(true);
}
public static void main(String args[])
{
SystemJava app = new SystemJava();
Training‐workshop on Object‐oriented Programming using Java
89 | P a g e
otherwise, the class is an abstract class and cannot be used to create objects. The use of event
listeners in event handling is known as delegation event model – the processing of an event is
delegated to a particular object in the program.
When an event occurs, the GUI component with which the user interacted notifies its
registered listeners by calling each listener’s appropriate event handling method. For example,
when the user presses the Enter key in a JTextField, the registered listener’s actionPerformed
method is called.
Example:
Figure 10.5: Calling the actionPerformed method
Code:
//Add this code to the Constructor of the previous example
TextFieldHandler listn = new TextFieldHandler();
txt1.addActionListener(listn);
txt2.addActionListener(listn);
txt3.addActionListener(listn);
pwd.addActionListener(listn);
String s = "";
if(e.getSource() == txt1)
{
s = "JTextField: " + e.getActionCommand();
}
else if(e.getSource() == txt2)
{
s = "JTextField with pre-defined text: " +
e.getActionCommand();
}
else if(e.getSource() == txt3)
{
s = "Uneditable Textfield: " + e.getActionCommand();
}
else if(e.getSource() == pwd)
{
s = "JPasswordField: " + e.getActionCommand();
}
JOptionPane.showMessageDialog(null, s);
}
}
Figure 10.5 shows a pop‐up message that displays the text value of whichever JTextField
triggers an ActionEvent. First, the JTextFields and JPasswordField are added with
actionListeners that will “listen” to any actionEvent the component will trigger. Then a class
TextFieldHandler which implements the ActionListener interface is created with the method
actionPerformed to be called upon the signal of the actionListener.
JButton
A button is a component the user clicks to trigger a specific action. A Java program can
create several types of buttons, including command buttons, check boxes, toggle buttons nad
radio buttons. A command button generates an ActionEvent when the user clicks the button
with the mouse. Command buttons are created with class JButton, which inherits from class
AbstractButton. The text on the face of a JButton is called a button label. A GUI can have many
JButtons, but each button label should be typically unique.
Constructors
Assume these declarations.
String text;
Icon image;
JButton btn = new JButton(text);
JButton btn = new JButton(text, image);
JButton btn = new JButton(image);
Training‐workshop on Object‐oriented Programming using Java
91 | P a g e
JCheckBox and JRadioButton
The Swing GUI components contain three types of state buttons – JToggleButton,
JCheckBox and JRadioButton – that have on/off or true/false values. JToggleButtons are
frequently used with toolbars (sets of small buttons typically located on a bar across the top of
the window). Classes JCheckBox and JRadioButton are subclasses of JToggleButton. A
JRadioButton is different from a JCheckBox in that there are normally several JRadioButtons
that are grouped together and only one of the JRadioButtons in the group can be selected
(true) at any time.
Common JRadioButton methods
rb.isSelected(); Returns true if that button is selected.
rb.setSelected(b); Sets selected status of a radio button
to b (true/false).
rb.addActionListener(an‐action‐listener); Adds an action listener to the radio button. The
action listener will be called if button is selected.
rb.addItemListener(an‐item‐listener); Add an item listener to a radio button. The item
listener will be called if the button is selected or
deselected.
JCheckBox Common Constructors
Assume
JCheckBox cb; // A checkbox.
String text; // Label on text box.
boolean state; // True/false state of checkbox.
new JCheckBox(text); Creates check box, initially unchecked.
new JCheckBox(text, state); Creates check box, checked or not depending on state.
cb.isSelected(); Returns true if the check box is checked.
cb.setSelected(state); Checks (true) or unchecks check box.
cb.addActionListener(action‐ Adds an action listener to the radio button. The action listener
listener); will be called if button is selected.
cb.addItemListener(item‐ Add an item listener to a radio button. The item listener will
listener); be called if the button is selected or deselected.
Example:
Training‐workshop on Object‐oriented Programming using Java
92 | P a g e
Figure 10.6: JButtons generates an actionEvent
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
SystemJava()
{
setTitle("Java Example");
Container c = getContentPane();
c.setLayout(new FlowLayout());
rbGroup.add(rb1);
rbGroup.add(rb2);
rb1.setSelected(true);
Training‐workshop on Object‐oriented Programming using Java
93 | P a g e
c.add(btn1);
c.add(btn2);
c.add(btn3);
c.add(rb1);
c.add(rb2);
c.add(cb1);
c.add(cb2);
c.add(cb3);
c.add(cb4);
setSize(150,300);
setResizable(false);
setVisible(true);
}
public static void main(String args[])
{
ButtonHandler app = new ButtonHandler();
WindowAdapter wAdapter=new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
};
app.addWindowListener(wAdapter);
}
private class CheckBoxHandler implements ItemListener
{
public void itemStateChanged(ItemEvent ie)
{
if (ie.getSource() == cb1)
{
if(ie.getStateChange() == ItemEvent.SELECTED)
{
cbChoice[0]="checked";
}
else
{
cbChoice[0]="unchecked";
}
}
if (ie.getSource() == cb2)
Training‐workshop on Object‐oriented Programming using Java
94 | P a g e
{
if(ie.getStateChange() == ItemEvent.SELECTED)
{
cbChoice[1]="checked";
}
else
{
cbChoice[1]="unchecked";
}
}
if (ie.getSource() == cb3)
{
if(ie.getStateChange() == ItemEvent.SELECTED)
{
cbChoice[2]="checked";
}
else
{
cbChoice[2]="unchecked";
}
}
if (ie.getSource() == cb4)
{
if(ie.getStateChange() == ItemEvent.SELECTED)
{
cbChoice[3]="checked";
}
else
{
cbChoice[3]="unchecked";
}
}
}
}
}
class ButtonHandler extends SystemJava implements ActionListener
{
ButtonHandler()
{
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
rb1.addActionListener(this);
rb2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==btn1)
{
btn1.setEnabled(false);
btn2.setEnabled(true);
}
else if(ae.getSource()==btn2)
Training‐workshop on Object‐oriented Programming using Java
95 | P a g e
{
btn1.setEnabled(true);
btn2.setEnabled(false);
}
if(ae.getSource()==rb1)
{
rbChoice = "Radio Button 1 is selected!";
}
else if(ae.getSource()==rb2)
{
rbChoice = "Radio Button 2 is selected!";
}
else if(ae.getSource()==btn3)
{
JOptionPane.showMessageDialog(null,rbChoice);
for(int counter=1;counter<5;counter++)
{
JOptionPane.showMessageDialog(null,"CheckBox"+counter+" is
"+cbChoice[counter-1]+"!");
}
}
}
}
Figure 10.6 shows 3 JButtons, 2 JRadioButtons, and 4 JCheckBoxes which are added with
an actionListener and itemListener. The 3 JButtons triggers an actionEvent through the
actionListener. The first JButton, btn1, disables btn2 when clicked. And btn2 disables btn1 when
clicked. btn3, when clicked, loops through and checks the JCheckBoxes’ state if it is selected or
not. JRadioButtons rb1 and rb2 are added to 1 ButtonGroup to specify an array of index for a
single JRadioButton group.
JComboBox
A combo box (sometimes called a drop‐down list) provides a list of items from which the
user can make a selection. Combo boxes are implemented with class JComboBox, which
inherits from class JComponent. JComboBox generate ItemEvents like JCheckBoxes and
JRadioButtons.
Example:
Figure 10.7: A JComboBox Example
Training‐workshop on Object‐oriented Programming using Java
96 | P a g e
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
SystemJava()
{
setTitle("Java Example");
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(cmb1);
c.add(lblChange);
setSize(300,100);
setVisible(true);
}
public static void main(String args[])
{
SystemJava app = new SystemJava();
Figure 10.7 shows a JComboBox which triggers an actionEvent when an index within the
choices is clicked. Whenever an index is clicked, it triggers the actionPerformed method and
invokes an ActionEvent. The program then identifies what index is selected and whatever item
it holds, it is parsed to a String value and is set to be the value for the JLabel lblChange.
JList
A list displays a series of items from which the user may select one or more items. Lists
are created with class JList, which inherits from class JComponent. Class JList supports single‐
selection lists (i.e., lists that allow only one item to be selected at a time) and ports single‐
selection lists (lists that allow any number of items to be selected).
Constructor:
String choices[]
JList listname= new JList(choices);
Multiple Selection Lists
A multiple‐selection list enables the user to select many items from a JList. A
SINGLE_INTERVAL_SELECTION list allows selection of a contiguous range of items in the list by
clicking the first item, then holding the shift key while clicking the last item to select in the
range. A MULTIPLE_INTERVAL_SELECTION list allows continuous range selection as described
for a SINGLE_INTERVAL_SELECTION list and allows miscellaneous items to be selected by
holding the Ctrl key while clicking each item to select. To deselect an item, hold the Ctrl key
while clicking an item the second time.
Constructor:
listname.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listname.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
listname.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
Example:
Figure 10.8: JLists
Training‐workshop on Object‐oriented Programming using Java
98 | P a g e
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
Container c = getContentPane();
c.setLayout(new FlowLayout());
list1.setVisibleRowCount(7);
list1.setSelectedIndex(0);
list1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
c.add(new JScrollPane(list1));
c.add(btn1);
c.add(btn2);
c.add(btn3);
c.add(btn4);
setSize(150,300);
setResizable(false);
setVisible(true);
}
public void chngeMode()
{
if(x==0)
{
list1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}
else if(x==1)
{
list1.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTI
ON);
}
else if(x==2)
{
Training‐workshop on Object‐oriented Programming using Java
99 | P a g e
list1.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELEC
TION);
}
}
public static void main(String args[])
{
ButtonHandler app = new ButtonHandler();
JOptionPane.showMessageDialog(null,list1.getSelectedValues());
}
else if(ae.getSource()==btn2)
{
x=0;
chngeMode();
JOptionPane.showMessageDialog(null,"Changed to SINGLE
SELECTION");
}
else if(ae.getSource()==btn3)
{
x=1;
chngeMode();
JOptionPane.showMessageDialog(null,"Changed to SINGLE
INTERVAL SELECTION");
}
else if(ae.getSource()==btn4)
{
x=2;
chngeMode();
Training‐workshop on Object‐oriented Programming using Java
100 | P a g e
JOptionPane.showMessageDialog(null,"Changed to
MULTIPLE INTERVAL SELECTION");
}
}
}
Figure 10.8 shows a JList and 3 JButtons to set the selection mode of the JList and a
Button to get the selected values. btn1, when clicked, creates a pop up message that displays
the selected values in the JList. btn2, btn3 and btn4 specifies the JList to be single selection,
single interval selection and multiple interval selection respectively.
Mouse Event Handling
Mouse events can be trapped for any GUI component that derives from
java.awt.Component. Each of the mouse event handling methods takes a MouseEvent object
as its argument. A MouseEvent object contains information about the mouse event that
occurred, including the x‐ and y‐ coordinates of the location where the event occurred. The
MouseListener and MouseMotionListener methods are called automatically when the mouse
interacts with a Component iflistener objects are registered for a particular Component.
Method mousePressed is called when a mouse button is pressed with the mouse cursor over a
component. Using methods and constants of a class InputEvent (the superclass of
MouseEvent), a program can determine which mouse button the user clicked. Method
mouseClicked is called whenever a mouse button is released without moving the mouse after a
mousePressed operation. Method mouseReleased is called whenever a mouse button is
released. Method mouseEntered is called when the mouse cursor enters the physical
boundaries of a Component. Method mouseExited is called when the mouse cursor leaves the
physical boundaries of a Component. Method mouseDragged is called when the mouse button
is pressed and held, and the mouse is moved (a process known as dragging). The
mouseDragged event is preceded by a mousePressed event followed by a mouseReleased
event. Method mouseMoved is called when the mouse is moved with the mouse cursor over a
component (with no mouse buttons pressed).
MouseListener and MouseMotionListener interface methods
public void mousePressed( MouseEvent e ) //MouseListener
Called when a mouse button is pressed with the mouse cursor on a component.
public void mouseClicked( MouseEvent e ) //MouseListener
Called when a mouse button is pressed and released on a component without moving
the mouse cursor.
public void mouseReleased( MouseEvent e ) //MouseListener
Called when a mouse button is released after being pressed. This event is always
Training‐workshop on Object‐oriented Programming using Java
101 | P a g e
preceded by the mousePressed event.
public void mouseEntered( MouseEvent e ) //MouseListener
Called when the mouse cursor enters the bounds of a component.
public void mouseExited( MouseEvent e ) //MouseListener
Called when the mouse cursor leaves the bounds of a component.
public void mouseDragged( MouseEvent e ) //MouseMotionListener
Called when the mouse button is pressed and the mouse is moved. This event is always
preceded by a call to mousePressed.
public void mouseMoved( MouseEvent e ) //MouseMotionListener
Called when the mouse is moved with the mouse cursor on a component.
Adapter Classes
Many event‐listener interfaces, such as MouseListener and MouseMotionListener,
contain multiple methods. It is not always desirable to declare every method in an event‐
listener interface. For instance, an application may need only the mouseClicked handler from
MouseListener or the mouseDragged handler from MouseMotionListener. Interface
WindowListener specifies seven window event‐handling methods. For many of the listener
interfaces that have multiple methods, packages java.awt.event and javax.swing.event provide
event‐listener adapter classes. An adapter class implements an interface and provides a default
implementation (with an empty method body) of each method in the interface. The figure
below shows several java.awt.event adapter classes and the interfaces they implement. You
can extend an adapter class to inherit the default implementation of every method and
subsequently override only the method(s) you need for event handling.
Event‐adapter classes in java.awt.event Implements interface
Component Adapter ComponentListener
Container Adapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
Figure 10.9: Event‐adapter classes and the interfaces they implement.
Training‐workshop on Object‐oriented Programming using Java
102 | P a g e
Keyboard Event Handling
This section presents the KeyListener interface for handling key events. Key events are
generated when keys on the keyboard are pressed and released. A class that implements
KeyListener must provide declarations for methods keyPressed, keyReleased and keyTyped,
each of which receives a KeyEvent as its argument. Class KeyEvent is a subclass of InputEvent.
Method keyPressed is called in response to pressing any key. Method keyTyped is called in
response to pressing any key that is not an action key. (The action keys are any arrow key,
Home, End, Page Up, Page Down, any function key, Num Lock, Print Screen, Scroll Lock, Caps
Lock and Pause.) Method keyReleased is called when the key is released after any keyPressed
or keyTyped event.
JTextArea
The JTextArea class provides a component that displays multiple lines of text and
optionally allows the user to edit the text.
Common JTextArea Constructors and methods:
new JTextArea(rows, cols); Creates textarea with specifed number of rows and columns.
ta.getText(); Returns string in text area.
ta.setText(s); Sets text to s.
ta.append(s); Adds s to end of existing text.
ta.insert(s, pos); Inserts s at position pos.
ta.setEditable(bool); Don't allow user to edit textarea if used for output.
ta.setLineWrap(bool); Allow/disallow long lines to wrap.
ta.setWrapStyleWord(bool); Call setLineWrap(true) first. true wraps at word boundaries, false
(default) at characters.
ta.setBorder(brdr); Add space between text and edge. Eg, to add 4 pixels
usebrdr BorderFactory.createEmptyBorder(4,4,4,4)
Example:
Figure 10.9: JTextArea
Training‐workshop on Object‐oriented Programming using Java
103 | P a g e
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
SystemJava()
{
setTitle("Java Example");
Container c = getContentPane();
c.setLayout(new FlowLayout());
txtArea1.setEnabled(false);
txtArea3.setEnabled(false);
txtArea1.setLineWrap(true);
txtArea2.setLineWrap(true);
txtArea3.setLineWrap(true);
txtArea1.setWrapStyleWord(true);
txtArea2.setWrapStyleWord(true);
txtArea3.setWrapStyleWord(true);
scrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROL
LBAR_ALWAYS);
scrollPane2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROL
LBAR_ALWAYS);
scrollPane3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROL
LBAR_ALWAYS);
scrollPane1.setPreferredSize(new Dimension(250, 250));
scrollPane2.setPreferredSize(new Dimension(250, 250));
scrollPane3.setPreferredSize(new Dimension(250, 250));
c.add(new JScrollPane(txtArea1));
c.add(lbl1);
c.add(new JScrollPane(txtArea2));
c.add(btn1);
c.add(btn2);
Training‐workshop on Object‐oriented Programming using Java
104 | P a g e
c.add(new JScrollPane(txtArea3));
setSize(300,500);
setResizable(false);
setVisible(true);
}
public static void main(String args[])
{
ButtonHandler app = new ButtonHandler();
JTextArea. The second JButton, when clicked, appends the highlighted text from the second
JTextAre to the third JTextArea.
Panels
The JPanel class provides general‐purpose containers for lightweight components.
Complex GUI’s require that each component be placed in an exact location. They often consist
of multiple panels with each panel’s components arranged in a specific layout. Panels are
created with class JPanel – a subclass of JComponent. Class JComponent inherits from class
java.awt.Container, so every JPanel is a Container. Thus, JPanels may have components,
including other panels, added to them.
Constructor:
JPanel p = new JPanel();
Adding components:
p.add(aComponent);
p.add(anotherComponent);
Example:
Figure 10.10: JPanels
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
Training‐workshop on Object‐oriented Programming using Java
106 | P a g e
Container c = getContentPane();
c.setLayout(new BorderLayout());
buttonPanel.setLayout(new GridLayout(1,5));
buttonPanel.add(btn1);
buttonPanel.add(btn2);
buttonPanel.add(btn3);
buttonPanel.add(btn4);
buttonPanel.add(btn5);
c.add(buttonPanel, BorderLayout.SOUTH);
setSize(600,300);
setVisible(true);
}
public static void main(String args[])
{
SystemJava app = new SystemJava();
table.getSelectedRow();
table.getSelectedColumn();
Example:
Figure 10.11: JTable
Code:
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.awt.*;
SystemJava()
{
setTitle("Java Example");
Container c = getContentPane();
c.setLayout(new BorderLayout());
pnl1.setLayout(new GridLayout(5,2));
pnl1.add(lblFName);
pnl1.add(txtFName);
pnl1.add(lblLName);
pnl1.add(txtLName);
pnl1.add(lblCourse);
pnl1.add(txtCourse);
pnl1.add(lblYear);
pnl1.add(txtYear);
pnl1.add(btn1);
pnl1.add(btn2);
table.setPreferredScrollableViewportSize(new Dimension(500,
70));
table.setFillsViewportHeight(false);
c.add(scrollPane, BorderLayout.CENTER);
c.add(pnl1, BorderLayout.EAST);
setSize(600,300);
setVisible(true);
}
public static void main(String args[])
{
ButtonHandler app = new ButtonHandler();
Training‐workshop on Object‐oriented Programming using Java
109 | P a g e
model.insertRow(table.getRowCount(),new
Object[]{txtFName.getText(),txtLName.getText(),txtCourse.getText(),txtY
ear.getText()});
}
else if(e.getSource()==btn2)
{
int rowIndex = table.getSelectedRow();
int colIndex = table.getSelectedColumn();
model.removeRow(rowIndex);
}
}
}
Figure 10.11 shows a JTable that indicates 5 rows of 4‐column data. Using the given
JTextFields and JButtons on the right, the JTable is manipulated. The user can append data onto
the table using the add button and can delete selected data from the table using delete button.
Layout Managers
Layout Managers are provided to arrange GUI components on a container for
presentation purposes. The layout managers provide basic layout capabilities that are easier to
use than determining the exact position and size of every GUI component. This enables the
programmer to concentrate on the basic “look and feel” and lets the layout manager process
most of the details.
FlowLayout
FlowLayout is the most basic layout manager. GUI components are placed on a
container from left to right in the order in which they are added to the container. When the
edge of the container is reached, components are continued on the next line. Class FlowLayout
allows GUI components to be left‐aligned, centered (default), and right‐aligned.
Example:
Figure 10.12: FlowLayout Layout Manager
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
SystemJava()
{
setTitle("Java Example");
Container c = getContentPane();
c.setLayout(new FlowLayout());
c.add(lbl1);
c.add(txt1);
c.add(lbl2);
c.add(txt2);
c.add(lbl3);
c.add(txt3);
c.add(btn1);
c.add(btn2);
setSize(350,150);
setVisible(true);
}
public static void main(String args[])
{
SystemJava app = new SystemJava();
WindowAdapter wAdapter=new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
};
app.addWindowListener(wAdapter);
}
}
Figure 10.12 shows a Container that displays GUI components using FlowLayout. Notice
that as the user resizes the container, the components added to the container adjust depending
on the width of the container.
Training‐workshop on Object‐oriented Programming using Java
111 | P a g e
BorderLayout
The BorderLayout layout manager (the default layout manager for the content pane)
arranges the components into five regions: North, South, East, West and Center (North
corresponds to the top of the container). Class BorderLayout inherits from Object and
implements interface LayoutManager2 (a subinterface of LayoutManager that adds several
methods for enhanced layout processing).
Up to 5 components can be added directly to a BorderLayout – one for each region. The
components placed in the North and South regions extend horizontally to the sides of the
container and are as tall as the components placed in those regions. The East and West regions
expand vertically between the North and South regions and are as wide as the components
placed in those regions. The component placed on the Center region expands to take all the
remaining space in the layout. If all five regions are occupied, the entire component’s space is
covered by GUI components. If the North or South region is not occupied, the GUI components
in the EAST, Center and West regions expand vertically to fill the remaining space. If the East or
West region is not occupied, the GUI component in the Center region expands horizontally to
fill the remaining space. If the Center region is not occupied, the area is left empty – the other
GUI components do not expand to fill the remaining space.
Example:
Figure 10.13: BorderLayout Layout Manager
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
SystemJava()
{
setTitle("Java Example");
Container c = getContentPane();
c.setLayout(new BorderLayout());
c.add(lbl1,BorderLayout.NORTH);
c.add(lbl2,BorderLayout.WEST);
c.add(txt1,BorderLayout.CENTER);
c.add(txt3,BorderLayout.EAST);
c.add(btn2,BorderLayout.SOUTH);
c.add(txt2,BorderLayout.CENTER);
setSize(600,300);
setVisible(true);
}
public static void main(String args[])
{
SystemJava app = new SystemJava();
Figure 10.13 shows a Container that displays GUI components using BorderLayout. As
discussed above, BorderLayout arranges components in five regions. Notice in the code, txt1 is
added to the container in the center region, and then txt2 is added again to the center region.
txt1 is overlapped by txt2 which is not above txt1, causing txt1 to be unseen on the container.
As the user will resize the container, the components added to each of the regions occupy the
space each region has.
Training‐workshop on Object‐oriented Programming using Java
113 | P a g e
GridLayout
The GridLayout layout manager divides the container into a grid so that components can
be placed into rows and columns. Class GridLayout inherits directly from class Object and
implements interface LayoutManager. Every Component in a GridLayout has the same width
and height. Components are added to a GridLayout starting at the top‐left cell of the grid and
proceeding left‐to‐right until the row is full. The process continues left‐to‐right on the next row
of the grid, etc.
Example:
Figure 10.14: GridLayout Layout Manager
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
SystemJava()
{
setTitle("Java Example");
c.setLayout(new GridLayout(3,2,5,5));
Training‐workshop on Object‐oriented Programming using Java
114 | P a g e
c.add(btn1);
c.add(btn2);
c.add(btn3);
c.add(btn4);
c.add(btn5);
c.add(btn6);
setSize(400,300);
setVisible(true);
}
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==btn1)
{
c.setLayout(new GridLayout(3,2,5,5));
c.setSize(400,300);
JOptionPane.showMessageDialog(null,"Layout: 3 rows, 2
columns, 5px horizontal space, 5px vertical space ");
}
else if(ae.getSource()==btn2)
{
Training‐workshop on Object‐oriented Programming using Java
115 | P a g e
c.setLayout(new GridLayout(2,3,5,5));
c.setSize(300,400);
JOptionPane.showMessageDialog(null,"Layout: 2 rows, 3
columns, 5px horizontal space, 5px vertical space ");
}
else if(ae.getSource()==btn3)
{
c.setLayout(new GridLayout(2,3));
JOptionPane.showMessageDialog(null,"Layout: 2 rows, 3
columns, 0px horizontal space, 0px vertical space ");
}
else if(ae.getSource()==btn4)
{
c.setLayout(new GridLayout(3,2));
JOptionPane.showMessageDialog(null,"Layout: 3 rows, 2
columns, 0px horizontal space, 0px vertical space ");
}
else if(ae.getSource()==btn4)
{
JOptionPane.showMessageDialog(null,"You clicked
button 5!");
}else if(ae.getSource()==btn4)
{
JOptionPane.showMessageDialog(null,"You clicked
button 6!");
}
}
}
Figure 10.14 shows a Container that displays GUI components using GridLayout.
JButtons are then added to the container and are arranged from left to right as specified by
GridLayout. JButtons btn1 and btn2 changes the number of rows and columns of the
GridLayout and specified with 5 pixels spacing between grids. JButtons btn3 and btn4 also
specifies the number of rows and columns, but this time does not invoke a positive value for
the horizontal and vertical spaces between cells.
BoxLayout
BoxLayout is a layout manager that allows GUI components to be arranged left‐to‐right
or top‐to‐bottom in a container. Class Box defines a container with BoxLayout as its default
layout manager and provides static methods to create a Box with a horizontal or vertical
BoxLayout.
Training‐workshop on Object‐oriented Programming using Java
116 | P a g e
Example:
Figure 10.15: BoxLayout Layout Manager
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
SystemJava()
{
setTitle("Java Example");
Container c = getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.X_AXIS));
btn1.setAlignmentY(c.CENTER_ALIGNMENT);
btn2.setAlignmentY(c.TOP_ALIGNMENT);
btn3.setAlignmentY(c.CENTER_ALIGNMENT);
btn4.setAlignmentY(c.CENTER_ALIGNMENT);
btn5.setAlignmentY(c.BOTTOM_ALIGNMENT);
btn6.setAlignmentY(c.CENTER_ALIGNMENT);
c.add(btn1);
c.add(Box.createHorizontalGlue());
c.add(btn2);
c.add(Box.createHorizontalGlue());
c.add(btn3);
c.add(Box.createHorizontalGlue());
c.add(btn4);
Training‐workshop on Object‐oriented Programming using Java
117 | P a g e
c.add(Box.createHorizontalGlue());
c.add(btn5);
c.add(Box.createHorizontalGlue());
c.add(btn6);
setSize(500,200);
setVisible(true);
}
Training‐workshop on Object‐oriented Programming using Java
118 | P a g e
Example:
Figure 10.16: CardLayout Layout Manager
Code:
import javax.swing.*;=
import java.awt.event.*;
import java.awt.*;
SystemJava()
{
setTitle("Java Example");
Container c = getContentPane();
c.setLayout(new FlowLayout());
Training‐workshop on Object‐oriented Programming using Java
119 | P a g e
panel1.setLayout(new BorderLayout());
panel2.setLayout(new BorderLayout());
panel1.setPreferredSize(new Dimension(280,200));
panel2.setPreferredSize(new Dimension(280,300));
panel1.add(lbl1, BorderLayout.CENTER);
panel2.add(btn1, BorderLayout.NORTH);
panel2.add(btn2, BorderLayout.SOUTH);
panel2.setVisible(false);
itmListn cmbhandler = new itmListn();
cb.addItemListener(cmbhandler);
c.add(cb);
c.add(cards);
setSize(300,400);
setResizable(false);
setVisible(true);
}
GridBagLayout
The most complex and most powerful of the predefined layout managers is
GridBagLayout. This layout is similar to GridLayout because GridBagLayout also arranges
components in a grid. However, GridBagLayout is more flexible. The components can vary in
size (i.e., they can occupy multiple rows and columns) and can be added in any order. The way
the program specifies the size and position characteristics of its components is by
specifying constraints for each component. The preferred approach to set constraints on a
component is to use the Container.add variant, passing it a GridBagConstraints object.
You can set the following GridBagConstraints instance variables:
gridx, gridy
Specify the row and column at the upper left of the component. The leftmost
column has address gridx=0 and the top row has address gridy=0.
UseGridBagConstraints.RELATIVE (the default value) to specify that the component be
placed just to the right of (for gridx) or just below (for gridy) the component that was
added to the container just before this component was added. We recommend
specifying the gridx and gridy values for each component rather than just
using GridBagConstraints.RELATIVE; this tends to result in more predictable layouts.
gridwidth, gridheight
Specify the number of columns (for gridwidth) or rows (for gridheight) in the
component's display area. These constraints specify the number of cells the component
uses, not the number of pixels it uses. The default value is 1.
Use GridBagConstraints.REMAINDER to specify that the component be the last
one in its row (for gridwidth) or column (for gridheight).
Use GridBagConstraints.RELATIVE to specify that the component be the next to last one
in its row (for gridwidth) or column (for gridheight). We recommend specifying
the gridwidth and gridheight values for each component rather than just
using GridBagConstraints.RELATIVE and GridBagConstraints.REMAINDER; this tends to
result in more predictable layouts.
Note: GridBagLayout does not allow components to span multiple rows unless the
component is in the leftmost column or you have specified
positivegridx and gridy values for the component.
fill
Used when the component's display area is larger than the component's
requested size to determine whether and how to resize the component. Valid values
(defined as GridBagConstraints constants) include NONE (the
default), HORIZONTAL (make the component wide enough to fill its display area
horizontally, but do not change its height), VERTICAL (make the component tall enough
Training‐workshop on Object‐oriented Programming using Java
121 | P a g e
to fill its display area vertically, but do not change its width), and BOTH (make the
component fill its display area entirely).
ipadx, ipady
Specifies the internal padding: how much to add to the size of the component.
The default value is zero. The width of the component will be at least its minimum width
plus ipadx*2 pixels, since the padding applies to both sides of the component. Similarly,
the height of the component will be at least its minimum height plus ipady*2 pixels.
insets
Specifies the external padding of the component ‐ the minimum amount of
space between the component and the edges of its display area. The value is specified
as an Insets object. By default, each component has no external padding.
anchor
Used when the component is smaller than its display area to determine where
(within the area) to place the component.
Valid values (defined as GridBagConstraints constants) are CENTER (the
default), PAGE_START, PAGE_END, LINE_START, LINE_END, FIRST_LINE_START,
FIRST_LINE_END, LAST_LINE_END, and LAST_LINE_START.
Here is a picture of how these values are interpreted in a container that has the
default, left‐to‐right component orientation.
Training‐workshop on Object‐oriented Programming using Java
122 | P a g e
distribute space among columns (weightx) and among rows (weighty); this is important
for specifying resizing behavior.
Unless you specify at least one non‐zero value for weightx or weighty, all the
components clump together in the center of their container. This is because when the
weight is 0.0 (the default), the GridBagLayout puts any extra space between its grid of
cells and the edges of the container.
Generally weights are specified with 0.0 and 1.0 as the extremes: the numbers in
between are used as necessary. Larger numbers indicate that the component's row or
column should get more space. For each column, the weight is related to the
highest weightx specified for a component within that column, with each multicolumn
component's weight being split somehow between the columns the component is in.
Similarly, each row's weight is related to the highest weighty specified for a component
within that row. Extra space tends to go toward the rightmost column and bottom row.
Example:
Figure 10.17: GridBagLayout Layout Manager
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
SystemJava()
{
setTitle("Java Example");
Training‐workshop on Object‐oriented Programming using Java
123 | P a g e
Container c = getContentPane();
c.setLayout(new GridBagLayout());
GridBagConstraints constraintz = new GridBagConstraints();
lbl1.setFont(new Font("Calibri",Font.BOLD,20));
constraintz.gridx = 0;
constraintz.gridy = 0;
constraintz.gridwidth = 2;
c.add(lbl1, constraintz);
constraintz.gridx = 0;
constraintz.gridy = 1;
constraintz.gridwidth = 1;
c.add(lblUName, constraintz);
constraintz.gridx = 1;
constraintz.gridy = 1;
constraintz.gridwidth = 1;
c.add(txtUName, constraintz);
constraintz.gridx = 0;
constraintz.gridy = 2;
constraintz.gridwidth = 1;
c.add(lblPwd, constraintz);
constraintz.gridx = 1;
constraintz.gridy = 2;
constraintz.gridwidth = 1;
c.add(pwdMyPass, constraintz);
constraintz.gridx = 1;
constraintz.gridy = 3;
constraintz.gridwidth = 1;
constraintz.anchor = GridBagConstraints.LAST_LINE_END;
c.add(btnSubmit, constraintz);
setSize(400,200);
setVisible(true);
}
public static void main(String args[])
{
SystemJava app = new SystemJava();
WindowAdapter wAdapter=new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
};
app.addWindowListener(wAdapter);
}
}
Training‐workshop on Object‐oriented Programming using Java
124 | P a g e
Figure 10.17 shows a container that arranges components using GridBagLayout. Like
GridLayout, the container is divided into grids and is added an additional functionality in
specifying how components will be added to each cell using GridBagConstraints. In GridBag
layout, the components are arranged from left‐to‐right while in GridBagLayout, we can specify
in which particular cell the component should be added to. Also, it can be specified, through a
set of GridBagConstraints values, how the component will look like when added into each cell.
JTabbedPanes
The JTabbedPane container allows many panels to occupy the same area of the
interface, and the user may select which to show by clicking on a tab. A tab may also be
selected by the program.
Constructor
JTabbedPane tabbedPane = new JTabbedPane(); // Defaults to tabs along the top edge.
JTabbedPane tabbedPane = new JTabbedPane(edge);
Where edge specifies which edge the tabs are on
JTabbedPane.TOP (default)
JTabbedPane.RIGHT
JTabbedPane.BOTTOM
JTabbedPane.LEFT
JFrames
A Frame is a top‐level window with a title and a border. The size of the frame includes
any area designated for the border. The dimensions of the border area may be obtained using
the getInsets method. A frame, implemented as an instance of the JFrame class, is a window
that has decorations such as a border, a title, and supports button components that close or
iconify the window. Applications with a GUI usually include at least one frame.
A JFrame is a window with a title bar and a border. Class JFrame is a subclass of
java.awt.Frame (which is a subclass of java.awt.Window). As such, JFrame is one of the few
Swing GUI components that is not a lightweight GUI component. When you display a window
from a Java program, the window is provided by the local platform’s windowing toolkit, and
therefore the window will look like every other window displayed on that platform. When a
Java application executes on a Macintosh and displays a window, the window’s title bar and
borders will look like those of other Macintosh applications. When a Java application executes
on a Microsoft Windows system and displays a window, the window’s title bar and borders will
look like those of other Microsoft Windows applications. And when a Java application executes
Training‐workshop on Object‐oriented Programming using Java
125 | P a g e
on a UNIX platform and displays a window, the window’s title bar and borders will look like
other UNIX applications on that platform.
Class JFrame supports three operations when the user closes the window. By default, a
window is hidden (i.e., removed from the screen). This can be controlled with JFrame method
setDefaultCloseOperation. Interface WindowConstants (package javax.swing), which class
JFrame implements, declares three constants—DISPOSE_ON_CLOSE, DO_NOTHING_ON_CLOSE
and HIDE_ON_CLOSE (the default)—for use with this method. Some platforms allow only a
limited number of windows to be displayed on the screen. Thus, a window is a valuable
resource that should be given back to the system when it is no longer needed. Class Window
(an indirect superclass of JFrame) declares method dispose for this purpose. When a Window is
no longer needed in an application, you should explicitly dispose of it. This can be done by
calling the Window’s dispose method or by calling method setDefaultCloseOperation with the
argument WindowConstants.DISPOSE_ON_CLOSE. Terminating an application will return
window resources to the system. Setting the default close operation to
DO_NOTHING_ON_CLOSE indicates that the program will determine what to do when the user
indicates that the window should be closed.
By default, a window is not displayed on the screen until the program invokes the
window’s setVisible method (inherited from class java.awt.Component) with a true argument. A
window’s size should be set with a call to method setSize (inherited from class
java.awt.Component). The position of a window when it appears on the screen is specified with
method setLocation (inherited from class java.awt.Component).
Figure 10.18: JFrame Container
Using Menus with Frames
Menus are an integral part of GUIs. Menus allow the user to perform actions without
unnecessarily cluttering a GUI with extra components. In Swing GUIs, menus can be attached
only to objects of the classes that provide method setJMenuBar. Two such classes are JFrame
and JApplet. The classes used to declare menus are JMenuBar, JMenu, JMenu‐Item,
JCheckBoxMenuItem and class JRadioButtonMenuItem. Class JMenuBar (a subclass of
Training‐workshop on Object‐oriented Programming using Java
126 | P a g e
JComponent) contains the methods necessary to manage a menu bar, which is a container for
menus. Class JMenu (a subclass of javax.swing.JMenuItem) contains the methods necessary for
managing menus. Menus contain menu items and are added to menu bars or to other menus as
submenus. When a menu is clicked, it expands to show its list of menu items.
Class JMenuItem (a subclass of javax.swing.AbstractButton) contains the methods
necessary to manage menu items. A menu item is a GUI component inside a menu that, when
selected, causes an action event. A menu item can be used to initiate an action, or it can be a
submenu that provides more menu items from which the user can select. Submenus are useful
for grouping related menu items in a menu.
Class JCheckBoxMenuItem (a subclass of javax.swing.JMenuItem) contains the methods
necessary to manage menu items that can be toggled on or off. When a JCheck‐ BoxMenuItem
is selected, a check appears to the left of the menu item. When the JCheck‐ BoxMenuItem is
selected again, the check is removed.
Class JRadioButtonMenuItem (a subclass of javax.swing.JMenuItem) contains the
methods necessary to manage menu items that can be toggled on or off like JCheckBox‐
MenuItems. When multiple JRadioButtonMenuItems are maintained as part of a Button‐
Group, only one item in the group can be selected at a given time. When a
JRadioButtonMenuItem is selected, a filled circle appears to the left of the menu item. When
another JRadioButtonMenuItem is selected, the filled circle of the previously selected menu
item is removed.
JDesktopPane and JInternalFrame
Many of today’s applications use a multiple‐document interface (MDI)—a main window
(called the parent window) containing other windows (called child windows), to manage several
open documents that are being processed in parallel. For example, many e‐mail programs allow
you to have several windows open at the same time, so you can compose or read multiple e‐
mail messages simultaneously. Similarly, many word processors allow the user to open multiple
documents in separate windows, making it possible to switch between them without having to
close one to open another.
Constructor:
JInternalFrame internalFrame;
internalFrame = new JInternalFrame(String title, boolean resizable, boolean closable,
Boolean maximizable, boolean iconifiable);
Training‐workshop on Object‐oriented Programming using Java
127 | P a g e
Example:
Figure 10.19: JInternalFrame
Code:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.awt.*;
public class SystemJava extends JFrame
{
JDesktopPane desktopPane;
JInternalFrame internalFrame;
JFrame mainFrame;
SystemJava()
{
mainFrame = new JFrame("All Frames in a JDesktopPane Container");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
desktopPane = new JDesktopPane();
internalFrame = new JInternalFrame("Internal Frame", true, true,
true, true);
internalFrame.setBounds(20, 20, 150, 100);
internalFrame.setVisible(true);
desktopPane.add(internalFrame);
internalFrame.setToolTipText("Internal Frame");
JMenuBar menubar = new JMenuBar();
JMenu myMenu = new JMenu("Count Total Frames");
myMenu.addMenuListener(new myMenu());
menubar.add(myMenu);
mainFrame.setJMenuBar(menubar);
mainFrame.add(desktopPane);
mainFrame.setSize(400,400);
mainFrame.setVisible(true);
}
Training‐workshop on Object‐oriented Programming using Java
128 | P a g e
Training‐workshop on Object‐oriented Programming using Java