Advanced Java Programming Chapter 3 - GUI Lecture
Advanced Java Programming Chapter 3 - GUI Lecture
Programming
To create and manipulate components and containers like buttons, labels, lists,
text fields and panels.
Overview
Swing Containers
Swing Components
Layout Management
Event Handling
Menu Usage
Command Line
Graphical User Interface - GUI: Visual communication between software and users.
Besides having a different look and feel from console-based programs, GUI-based programs follow a different
program execution paradigm – event-driven programming.
A console-based program begins and ends in its main() method. To solve the problem, the main method statements
Overview
The execution of a GUI-based program also begins in its main() method. Normally the
main method is responsible only for creating an instance of the GUI.
After creating the GUI, the flow of control passes to an event-dispatching loop that
repeatedly checks for user interactions with the GUI through action events.
When an event occurs, an action performer method is invoked for each listener of that
event. The performer then processes the interaction.
After the performer handles the event, control is given again to the event-dispatching loop
to watch for future interactions.
This process continues until an action performer signals that the program has
completed its task.
Overview
Computer users today expect to interact with their computers using a graphical user interface (GUI). Java can be
used to write GUI programs ranging from simple applets which run on a Web page to sophisticated stand-alone
applications.
These interfaces provide the user with multiple windows on the screen and support the use of a mouse to click on
buttons, drag items around, pull down and select items from menus, select text fields in which to type responses,
scroll through windows, and perform many other operations.
A major part of creating a graphical user interface in Java is figuring out how to position and lay out the
components of the user interface to match the appearance you desire.
Once you have chosen and laid out these components, you must make the events interactive by making them
respond to various user events such as button clicks or mouse movements.
Overview
Thus, we will learn to make our interfaces graphical, so we can use our programs through windows, click o
buttons, etc.
For Java based graphical user interface we have the following packages:
import java.awt.*;
import javax.swing.*;
AWT is fine for developing simple graphical user interfaces, but not for developin
comprehensive GUI projects.
Besides, AWT is prone to platform-specific bugs because its peer-based approach relies heavil
on the underlying platform. With the release of Java 2, the AWT user-interface components wer
Overview
Swing components are painted directly on canvases using Java code, except for components that are subclasses
of java.awt.Window or java.awt.Panel, which must be drawn using native GUI on a specific platform. Swing
components are less dependent on the target platform and use less of the native GUI resource.
Before Swing, the only option that Java GUI developers had was to use AWT (Abstract Widget Toolkit).
However, because of limitations in AWT, such as the number of components and portability issues, Sun
introduced Swing.
From a programmer's perspective, Swing is an alternative to using the AWT, although technically Swing
extends (but does not replace) the AWT.
Swing components that don’t rely on native GUI are referred to as lightweight components, and AWT
components are referred to as heavyweight components.
Overview: AWT Vs. Swing
AWT SWING
AWT(JDK 1.0, 1.1): Abstract Window Toolkit Second Edition
Swing inherits from AWT
Sun initial idea.
can be customized
Not powerful enough. Allow much power full computer graphics.
package: java.awt, java.awt.event Use prefix “J” to differentiate it from awt components and
containers
heavyweight components using native GUI system
Swing(Java 2, JDK 1.2+)
elements
lightweight components that do not rely on the native GUI or OS
used for applets until most browsers supported JRE 1.2 “look and feel” of Swing components
are identical on different platforms
AWT still used for events, layouts
Overview: Some AWT and Swing Classes
Overview: AWT Pros and Cons
Pros Cons
Portability: use of native peers creates
Speed: native components speed performance.
platform specific limitations. Some
Look and feel: AWT components more closely components may not function at all on some
platforms.
reflect the look and feel of the OS they run on. Features: AWT supports only the lowest
common denominator—e.g. no tool tips or
Applet Portability: most Web browsers support
icons.
AWT classes so AWT applets can run without Third Party Development: the majority of
the Java plugin. component makers, including Borland and
Sun, base new component development on
Swing components.
Overview: Swing Pros and Cons
Pros Cons
Applet Portability: Most Web browsers do not include the Swing
Portability: Pure Java design provides for fewer platform
specific limitations. classes, so the Java plugin must be used.
Behavior: Pure Java design allows for a greater range of
Performance: Swing components are generally slower and buggier
behavior for Swing components since they are not limited by
the native peers that AWT uses. than AWT, due to both the fact that they are pure Java and to video
Features: Swing supports a wider range of features like issues on various platforms. Since Swing components handle their
icons and pop-up tool-tips for components.
own painting (rather than using native API’s like DirectX on
Vendor Support: Swing development is more active. Sun puts
much more energy into making Swing robust. Windows) you may run into graphical glitches.
Look and Feel: The pluggable look and feel lets you design a Look and Feel: Even when Swing components are set to use the look
single set of GUI components that can automatically have the
look and feel of any OS platform (Microsoft Windows, and feel of the OS they are run on, they may not look like their native
Solaris, Macintosh, etc.). It also makes it easier to make counterparts.
global changes to your Java programs that provide greater
accessibility (like picking a hi-contrast color scheme or
changing all the fonts in all dialogs, etc.).
Overview: Swing Stack
Swing does not replace the AWT; it is built on top of it
2. Functionality
Define the user-components interaction
3. Considerations
Programmatic – Declarative – Visual
Main Steps in GUI Programming
To make any graphic program work we must be able to create windows and add content to
them.
FontMetrics
Graphics
Lightweight
GUI Class Hierarchy: Container Classes
FontMetrics
Graphics
Lightweight
GUI Class Hierarchy: Helper Classes
FontMetrics
Graphics
The helper classes are not subclasses of Component. They JComponent Swing Components
JPanel
are used to describe the properties of GUI components such in the javax.swing package
as graphics context, colors, fonts, and dimension.
Lightweight
GUI Class Hierarchy: Swing Components
JCheckBoxMenuItem
JMenuItem
JMenu
JToggleButton JCheckBox
JComponent
JEditorPane JRadioButton Components Covered in the
JTextComponent Comprehensive Version
JTextField JPasswordField
JTextArea
TextArea
Graphics List
Component Choice
CheckBox
LayoutManager CheckBoxGroup
Canvas
MenuBar
Scrollbar
Simple GUI for I/O with JOptionPane
The simplest way to create a graphical window in Java is to have an option pane pop up.
An option pane is a simple message box that appears on the screen and presents a message or a
request for input to the user.
The Java class used to show option panes is called JOptionPane. JOptionPane belongs to the
javax.swing package, so you’ll need to import this package to use it.
JOptionPane can be used in three major ways: to display a message, to present a list of choices
to the user, and to ask the user to type input. The three methods that implement these three
behaviors are called showMessageDialog, showConfirmDialog, and showInputDialog,
respectively.
Simple GUI for I/O with JOptionPane
Message dialog type
ERROR_MESSAGE A dialog that indicates an error to the user.
QUESTION_MESSAGE A dialog that poses a question to the user. This dialog normally
requires a response, such as clicking a Yes or a No button.
import javax.swing.JOptionPane;
public class AdditionWW{
public static void main(String[] args){
String firstnumber= JOptionPane.showInputDialog("Enter First Numbers");
String secondnumber=JOptionPane.showInputDialog("Enter second Numbers");
int num1=Integer.parseInt(firstnumber);
int num2=Integer.parseInt(secondnumber);
int sum = num1 +num2;
JOptionPane.showMessageDialog(null,"the sum this two number is ="+sum,"this
result dialog", JOptionPane.PLAIN_MESSAGE);
}
}
Containers
A container is a component which can contain other components inside itself.
Other containers include windows, frames, dialogs, and panels. Containers may contain
other containers.
Since containers are themselves components, containers may by placed inside other
containers
Applets provide a ready-made container and a default LayoutManager, a
FlowLayout.
Two different kinds of containers:
Panels: contained inside another container, or perhaps inside the web browser's window.
Windows: a free-standing, native window.
There are two kinds of windows:
Frames: represents a normal, native window.
Dialogs: a transitory window that exists merely to impart some information or get some
input from the user.
Containers: Windows
A Frame is what most people think of as a window in their native environment.
it will hang around on the screen as long as the user is interested in the content of the window.
Its purpose is to get some particular information from the user (input) or to impart some particularly important
information to the user (output).
It is normally visible on the screen only until it gets the input or receives acknowledgement from the user about its
output.
Windows: Frame
JOptionPane is useful, but on its own it is not flexible or powerful enough to create rich
graphical user interfaces.
Frame: A graphical window on the screen. A window with a title bar, a resizable border,
and possibly a menu bar.
A frame is not attached to any other surface.
It has a content pane that acts as a container.
The container uses BorderLayout by default.
Frames are represented by objects of the JFrame class. Any complex graphical program
must construct a JFrame object to represent its main graphical window.
Once you’ve constructed a JFrame object, you can display it on the screen by calling its
setVisible method and passing it the boolean value true.
Component: A widget, such as a button or text field, that resides inside a graphical
window.
Windows: Frame anatomy
JFrame is the application window class
It is special; it draws the window and interacts with the operating system
When a JFrame is created, an inner container called the contentPane is
automatically created
We don't draw graphics directly on JFrame; we draw on the
contentPane
title bar
minimize
maximize
close
However you can change this using the frame's setLayout() method like this:
f.setLayout(new FlowLayout());
If you want to draw in the frame and process events manually, just create a
subclass of Frame and add listener objects to it.
Windows: Frame Example
Therefore, a lot of what you learned about frames applies to dialogs as well. You move them,
resize them and add to them almost exactly as you do frames.
A modal dialog blocks all other use of the application until the user responds to it.
A modal dialog cannot be moved and does not allow the user to switch to another window in the
same program.
On some platforms the user may not even be able to switch to another program
Windows: Dialogs Methods
Non-modal dialogs pop-up but they don't prevent the user from doing other things while they're
visible.
Because modal dialogs inconvenience users by forcing them to respond when the computer wants
them to rather than when they want to, their use should be kept to a minimum.
The only methods that are significantly different between a dialog and a frame are the
constructors.
There are two constructors for Dialog which differ in whether or not the dialog is given a title.
Dialog d = new Dialog(new Frame( ), false);
The second argument is a boolean which specifies whether or not the dialog should be modal.
Modal dialogs are only modal relative to their parent frame, which is passed as the first argument
to the constructor. That is they block input to the parent frame but not to other frames.
Windows: Dialogs Methods
There are also some common differences between most frames and most dialogs, but these are not
written in stone:
Most Frames can be moved and resized by the user. Most Dialogs cannot be.
You can make a dialog resizable and movable by calling its setResizable() method with a boolean
value of true like this:
d.setResizable(true);
You can give a dialog a title bar by adding the title string to the constructor:
All the other methods of the Dialog class are exactly the same as they are for Frames.
Panels as Sub containers
A panel is a type of container that's designed to hold a group of components so they can be
displayed on a frame.
The normal way to display a group of controls such as text fields, labels, buttons, and other
GUI widgets is to add those controls to a panel, and then add the panel to the frame.
You can bypass the panel and add the controls directly to the frame if you want, but using a
separate panel to hold the frames control is almost always a good idea.
The default layout manager of both Panel and JPanel is FlowLayout, but since they are
containers, they can have any layout manager assigned to them.
Panels as Sub containers
A Panel is a fairly generic Container whose primary purpose is to subdivide the
drawing area into separate rectangular pieces.
Since each Panel can have its own LayoutManager, you can do many things with
panels that you can't do with a single LayoutManager.
panel.setBounds(40,80,200,200); }
public static void main(String args[])
panel.setBackground(Color.gray);
{
JButton b1=new JButton("Button 1");
new PanelExample();
b1.setBounds(50,100,80,30); }
b1.setBackground(Color.yellow); }
Components
GUI’s are built from GUI components. These are sometimes called controls or widgets (short for
windows gadgets) in languages other than Java.
Many applications that you use on a daily basis use windows or dialog boxes (also called dialogs)
to interact with the user.
GUI components (sometimes called “widgets”) are items like buttons and menus that can be
added to the user interface to provide a way for users to interact with a program.
A GUI program offers a much richer type of user interface, where the user uses a mouse and
keyboard to interact with GUI components such as windows, menus, buttons, check boxes, text
input boxes, scroll bars, and so on.
Components
Components: Using a GUI Component
1. Create it
2. Configure it
3. Add children (if container) Order is important
To create a component:
ComponentClassName obj = new ComponentConstructor();
JComponent: The base class for all Swing components except top-level containers
Swing Components
High-Level Containers Text Editing Components
JFrame, JDialog, JWindow, JTextField, JFormattedTextField,
JInternalFrame, JApplet JPasswordField, JTextArea,
JEditorPane, JTextPane
Intermediate Containers
Menus
JPanel, JScrollPane, JSplitPane,
JTabbedPane, JDesktopPane, JMenuBar, JMenu, JPopupMenu,
JToolBar JMenuItem,
JCheckboxMenuItem,
Atomic Components JRadioButtonMenuItem
JLabel, JButton, JCheckBox, Complex Components
JRadioButton, JToggleButton,
JScrollBar, JSlider, JProgressBar, JTable, JTree, JComboBox,
JSeparator JSpinner, JList, JFileChooser,
Label
The Label component allows for the display of fixed text strings in a container such as a Panel.
To create a label, use the JLabel class JLabel (which is a subclass of JComponent).
A typical GUI consists of many components. In a large GUI, it can be difficult to identify the
purpose of every component unless the GUI designer provides text instructions or information
stating the purpose of each component and such text is known as a label.
A JLabel displays a single line of read-only (noneditable) text, an image, or both text and an
image.
Label
Labels are used for a variety of purposes:
to display captions for other controls such as text fields or combo boxes,
And you have complete control over the appearance of the text.
You can specify the font, size, whether the text is bold, italic, or underlined, what color the
text is displayed as, and so on.
Label: Commonly used Constructors:
Constructor Description
JLabel() Creates a JLabel instance with no image and
with an empty string for the title.
JButton()
JButton(String label)
Methods
void setEnabled (boolean value): - Enables or disables the button. The default setting is true (enabled).
void setText (String text): - Sets the text displayed by the button.
void setVisible (boolean value): - Shows or hides the button. The default setting is true (the button is visible).
Button: Example
package buttonexample;
import javax.swing.*;
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
Text Fields
They are single-line areas in which text can be entered by the user from the keyboard or text can
simply be displayed .
To create a text field, use the JTextField class. An object from the class JTextField displays a single line
of user-updatable text.
A user may change the contents of a JTextField object by clicking in the field and typing new text. Thus
JTextFields are very useful for obtaining user input.
Text fields are created using the built-in JTextField class that is part of Java’s Swing package. One
constructor takes an int representing the width of the field in characters (approximately). Others take
an initial string as a parameter or both.
JTextField(int columns): - Creates an empty text field with the specified number of columns.
JTextField(String text): - Creates a text field initialized with the specified text.
JTextField(String text, int columns): - Creates a text field initialized with the specified text and the column
size.
Methods
setColumns(int): - Sets the number of columns in this text field. The length of the text field is changeable.
Constructor
wordField(String text, int columns) - constructs a new password field.
Methods
void setEchoChar(char echo) - sets the echo character for this password field. A value of
0 resets the echo character to the default.
Constructors
JTextArea(int rows, int columns) - Creates a text area with the specified number of rows and
columns.
JTextArea(String s, int rows, int columns) - Creates a text area with the initial text and the
number of rows and columns specified.
Text Areas: Example
package textareaexample;
import javax.swing.*;
public class TextAreaExample {
TextAreaExample(){
JFrame f= new JFrame();
JTextArea area=new JTextArea("This JText Area");
area.setBounds(10,30, 200,200);
f.add(area);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true); }
public static void main(String args[]) {
new TextAreaExample(); }}
Check Box
If you want to collect just a “yes” or “no” input, use a check box component.
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false).
Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".
Constructor
JCheckBox(String label)
Methods
boolean isSelected ()
If you have more than a handful of alternatives, radio buttons are not a good choice because
they take up too much screen space.
A combo box, also known as a choice list or drop-down list, contains a list of items from which
the user can choose.
A combo box is useful for limiting a user’s range of choices and avoids the cumbersome
validation of data input.
The first item is added at index 0; The first item added to a JComboBox appears as the
currently selected item when the JComboBox is displayed.
When clicked, the JComboBox expands into a list from which the user can make a selection.
Combo Boxes (drop-down list)
Commonly used Constructors and Methods
Constructor Description
Methods Description
void addItem(Object anObject) It is used to add an item to the item list.
void removeItem(Object anObject) It is used to delete an item to the item list.
void removeAllItems() It is used to remove all the items from the list.
void setEditable(boolean b) It is used to determine whether the JComboBox is editable.
Constructor Description
JList() Creates a JList with an empty, read-only, model.
Constructor Description
JScrollBar() Creates a vertical scrollbar with the
initial values.
JScrollBar(int orientation) Creates a scrollbar with the specified
orientation and the initial values.
JScrollBar(int orientation, int value, Creates a scrollbar with the specified
int extent, int min, int max) orientation, value, extent, minimum,
and maximum.
Scroll Bars
Example
package scrollbarexample;
import javax.swing.*;
class ScrollBarExample {
ScrollBarExample(){
JFrame f= new JFrame("Scrollbar Example");
JScrollBar s=new JScrollBar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true); }
public static void main(String args[]) {
Scroll Pane(Container)
A JscrollPane is used to make scrollable view of a component. When screen size is limited,
we use a scroll pane to display a large component or a component whose size can change
dynamically.
The JList component, for example, does not handle scrolling on its own. Instead, it
concentrates on presenting the list and making selection easy, assuming you'll put it inside a
JScrollPane if you need scrolling.
A similar technique can be used with many of the Swing components, including JPanel,
JTable, and JTextArea.
Scroll Pane(Container)
Constructor Purpose
JScrollPane() It creates a scroll pane. The Component parameter, when
present, sets the scroll pane's client. The two int parameters,
JScrollPane(Component) when present, set the vertical and horizontal scroll bar policies
JScrollPane(int, int) (respectively).
JScrollPane(Component, int, int)
Component getRightComponent() It returns the component to the right (or below) the divider.
SplitPaneUI getUI() It returns the SplitPaneUI that is providing the current look and
feel.
boolean isContinuousLayout() It gets the continuousLayout property.
boolean isOneTouchExpandable() It gets the oneTouchExpandable property.
void setOrientation(int orientation) It gets the orientation, or how the splitter is divided.
Split Pane(Option, Comp1, Comp2)
Example // set flow layout for the frame
createAndShow(); } }); } }
Tabbed Pane
A JTabbed Pane arranges GUI components into layers, of which only one is visible at a time.
When the user clicks a tab, the appropriate layer is displayed.
Any component can be placed on a tab.
If the component is a container, such as a panel, it can use any layout manager to lay out several
components on the tab.
public void addTab(String title, Component comp)
public void addTab(String title, Icon tabIcon, Component comp)
public void addTab(String title, Icon tabIcon, Component comp, String tip)
Table
Tables represent one of the most common formats for viewing data.
The JTable class is a part of Java Swing Package and is generally used to display or edit two-
dimensional data that is having both rows and columns. It is similar to a spreadsheet.
Rather than adding the table itself directly to our window, we enclose it in a scrollpane:
Constructors in JTable:
JTable(Object[][] data, Object []Column): A table is created with the specified name where []Column
defines the column names.
Table:
Create the following table
Table: Example
package tableexample; String
import javax.swing.*; column[]={"ID","NAME","SEX","AGE","D
public class TableExample { EPATMENT","CLASS YEAR","GPA"};
JFrame f;
TableExample(){ JTable jt=new JTable(data,column);
f=new JFrame(); jt.setBounds(30,40,200,300);
String data[][]={ JScrollPane sp=new JScrollPane(jt);
{"101","Helen","F","22","Computer Science","3rd f.add(sp);
Year","3.25"},
f.setSize(300,400);
{"102","Melat","F","21","Software Eng","3rd Year","3.02"},
f.setVisible(true);
{"101","Sada","F","23","Information Technology","3rd }
Year","3.6"},
{"101","Hussen","M","23","Information Science","2nd
public static void main(String[] args) {
Year","3.9"}, new TableExample();
{"101","Seid","M","22","Information System","2nd
}
Year","3.7"}
}; }
File Chooser
A special dialog box that allows the user to select one or more files/folders
Asking a user to type a path and file name is a bad idea.
public JFileChooser()
public JFileChooser(String currentDir)
public int showOpenDialog(Component parent)
public int showSaveDialog(Component parent)
public File getSelectedFile()
public static int APPROVE_OPTION, CANCEL_OPTION Possible result values from
showXxxDialog(..).
We want a ‘point and click’ type interface to get a file name.
JFileChooser myChooser = new JFileChooser();
myChooser.showOpenDialog(this);
String file=myChooser.getSelectedFile().toString();
File Chooser Example
if (a == JFileChooser.APPROVE_OPTION) {
File fileToOpen = fileChooser.getSelectedFile();
Desktop.getDesktop().open(fileToOpen);
}
}
Formatted Text Field
Mask Formatter
It is not intended to be used as a full-featured web browser, but it can be used to view simple
HTML and is ideal for integrating online help into Java applications.
setPage(URL) Loads an editor pane (or text pane) with the text at the specified
setPage(String) URL.
URL getPage() Gets the URL for the editor pane's (or text pane's) current page.
JEditorPane (JEditorPane is a kind of text area
that can display various text formats. )
package jeditorpaneexample;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
public class JEditorPaneExample {
JFrame myFrame = null;
public static void main(String[] a) {
(new JEditorPaneExample()).test(); }
private void test() {
myFrame = new JFrame("JEditorPane Test");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(400, 200);
JEditorPane myPane = new JEditorPane();
myPane.setContentType("text/plain");
myPane.setText("Sleeping is necessary for a healthy body."
+ " But sleeping in unnecessary times may spoil our health, wealth and studies."
+ " Doctors advise that the sleeping at improper timings may lead for obesity during the students days.");
myFrame.setContentPane(myPane);
myFrame.setVisible(true); } }
Tool Bar
JToolBar container allows us to group other components, usually buttons with icons in a row
or column.
JToolBar provides a component which is useful for displaying commonly used actions or
controls.
JToolBar(int orientation) It creates a new tool bar with the specified orientation.
JToolBar(String name) It creates a new tool bar with the specified name.
JToolBar(String name, int orientation) It creates a new tool bar with a specified name and
orientation.
Tool Bar
Layout Management
(Arranging Elements in Windows)
You may be wondering why we don’t just specify the size and location of
components in the window, as we did with graphics objects on the canvas, rather
than depending on layout managers and panels to arrange them.
One reason is that the user can resize the window at any time. It would be very
inconvenient to have the user resize the window so that some of the components
were no longer visible.
Layout management is the process of determining the size and location of a
container's components.
Java containers do not handle their own layout. They delegate that task to their
layout manager, an instance of another class.
If you do not like a container's default layout manager, you can change it.
Container content = getContentPane();
content.setLayout( new FlowLayout() );
Layout Management
When building a GUI, each GUI component must be attached to a container, such as a
window created with a JFrame.
Typically, you must also decide where to position each GUI component within the container.
Some types of layout managers (e.g. FlowLayout) choose to size the components
inside them to the preferred size; others (e.g. BorderLayout, GridLayout)
disregard the preferred size and use some other scheme
Layout Management
Layout managers control:
Where components appear
What sizes they are
How they react when they are
resized
Layout managers control the size and
arrangement of components in a container.
There are 6 common layout managers:
1. FlowLayout
2. BorderLayout
3. GridLayout
4. GridBagLayout
5. BoxLayout
6. CardLayout
Flow Layout
The component objects appear in order in which they are added to the container
from left to right until no more component will fit on a row. It then moves to the
next row and continue going left to right.
A flow layout arranges components in a directional flow one after the other,
moving onto a new line when no more components ft on the current line.
Direction is determined by the container’s componentOrientation property and
may be one of two values:
ComponentOrientation.LEFT_TO_RIGHT or
ComponentOrientation.RIGHT_TO_LEFT
FlowLayout, the simplest of the managers, simply adds components left to
right until it can fit no more within its container's width.
It then starts a second line of components, fills that, starts a third, etc.
Each line is centered in the container
Flow Layout
FlowLayout respects each component's preferred size and will use it to override a size set by
setSize.
Flow layout is the default layout manager for AWT and Swing components.
Constructors
FlowLayout();
As each component is added to a container with a border layout, the location is specified similar to:
container.add(component, BorderLayout.CENTER);
Constructor:
BorderLayout(int n, int m); //n pixel gaps
Methods
void add(Component cp, int region);
Constructor:
GridLayout(int row, int col);
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
Eg. new GridLayout(4,3);
Grid Bag Layout
Divides the window into grids, without requiring the components to be the same size.
Each component managed by a grid bag layout is associated with an instance of
GridBagConstraints.
The GridBagConstraints specifies:
How the component is laid out in the display area
In which cell the component starts and ends
How the component stretches when extra room is available
Alignment in cells
Grid Bag Layout
To describe the layout to the grid bag manager, use the following procedure:
1. Create an object of type GridBagLayout.
You don’t tell it how many rows and columns the underlying grid has. Instead, the layout manager will
try to guess it from the information you give it later.
2. Set this GridBagLayout object to be the layout manager for the component.
3. For each component, create an object of type GridBagConstraints.
Set field values of the GridBagConstraints object to specify how the components are laid out within the
grid bag.
4. Finally, add each component with its constraints by using the call
add(component, constraints);
Grid Bag Layout
Far more advanced than any of the other layout managers.
It is flexible layout manager that aligns components both vertically and horizontally, without
requiring that the components be the same size.
It maintains a dynamic grid of cells where components can be placed and where the components
can occupy one or more of the cells.
Constructor:
public GridBagLayout()
Constraints:
gridx, gridy
gridwidth, gridheight
fill
Grid Bag Layout
• gridwidth 1 The component will occupy a single cell within the layout. fill NONE The component should not resize itself if extra space is
• gridheight 1 The component will occupy a single cell within the layout. available within its region.
gridConstraints.fill = GridBagConstraints.BOTH;
Grid Bag Layout
1. Set the layout, saving a reference to it
GridBagLayout layout = new GridBagLayout();
setLayout(layout);
2. Allocate a GridBagConstraints object
GridBagConstraints constraints = new GridBagConstraints();
3. Set up the GridBagConstraints for component 1
constraints.gridx = x1;
constraints.gridy = y1;
constraints.gridwidth = width1;
constraints.gridheight = height1;
4. Add component 1 to the window, including constraints
add(component1, constraints);
gridConstraints.gridx = 1;
gridConstraints.gridy = 3;
gridConstraints.gridheight = 2;
gridConstraints.gridwidth = 3;
add(component, gridConstraints);
Card Layout
The CardLayout layout manager is significantly different from the other layouts. Whereas the
other layout managers attempt to display all the components within the container at once, a
CardLayout displays only one component at a time.
Card Layout is a simple layout manager that treats each component as a card.
The first component added to the container is visible by default when the container is initially
displayed.
This manager has a limited practical use. It can be used to create a wizard or a tabbed pane.
Card Layout
Panel cardPanel;
…
CardLayout layout new CardLayout();
cardPanel.setLayout(layout);
...
cardPanel.add("Card 1", component1);
cardPanel.add("Card 2", component2);
...
layout.show(cardPanel, "Card 1");
layout.first(cardPanel);
layout.next(cardPanel);
Box Layout
BoxLayout manager is a simple layout manager that organizes components in a column or a row.
BoxLayout is only able to create fixed spaces; therefore, its layouts are not portable.
Unlike other layout managers, BoxLayout takes a container instance as the first parameter in the
constructor.
The second parameter determines the orientation of the manager. To create a horizontal box, we
can use the LINE_AXIS constant. To create a vertical box, we can use the PAGE_AXIS
constant.
Box Layout Example
Layout Management: pack()
pack() method rearranges components such that any unused space is not shown
Adjusts the size of the frame to fit the components added to it.
How would you create a complex window like
this?
SOLUTION: COMPOSITE LAYOUT
CREATE PANELS WITHIN PANELS EACH PANEL HAS A DIFFERENT LAYOUT, AND BY COMBINING THE LAYOUTS, MORE
COMPLEX / POWERFUL LAYOUT CAN BE ACHIEVED
Event Handling
How do GUIs interact with users? How do applications recognize when the user has done something?
Any operating system that supports GUIs constantly monitors events such as keystrokes and mouse clicks.
The operating system reports these events to programs that are running.
The programs decide what, if anything, they want to do with these events.
In Java, you control how to handle these events by setting up event source objects and event listener objects.
Event Handling
An event can be defined as a type of signal to the program that something has
happened.
The event is generated by external user actions such as mouse movements, mouse
button clicks, and keystrokes, or by the operating system, such as a timer.
Events are responded to by event listeners.
Each event-generating object (usually a component) maintains a set of listeners
for each event that it generates.
To be on the list, a listener object must register itself with the event-generating
object.
Listeners have event-handling methods that respond to the event.
3. Indicate that an object of the class from Steps 1 and 2 should be notified when the event occurs.
This is known as registering the event handler.
A user interaction creates an event Common events are clicking a button, typing in a text field,
selecting an item from a menu, closing window and moving the mouse. The event causes a call
to a method called an event handler.
Event Handling
NOTE: any object that will respond to an event must implement a listener
interface.
Event Handling
Currently, the views painted by the application frame with its constituent
components are like empty shells with no application processing logic underneath.
Event Handling
Semantic events express what the user is doing.
e.g. clicking a button
Low-level events are those that make semantic events possible.
e.g. mouse moves, mouse clicks, keyboard strokes etc.
The 4 semantic event classes in java.awt.event package
ActionEvent
(for button clicks, menu selections, ENTER typed in text field, selecting a list item)
AdjustmentEvent
(the user adjusted a scroll bar)
ItemEvent
(the user made a selection from a set of checkboxes or list items)
TextEvent
(the contents of a text field or text area were changed)
Event Handling
The 7 low-level event classes in java.awt.event package
ComponentEvent
(the component was resized, moved, shown, or hidden)
KeyEvent
(key was pressed or released)
MouseEvent
(the mouse button was pressed, released, moved, or dragged)
MouseWheelEvent
(the mouse wheel was rotated)
FocusEvent
(a component got focus or lost focus)
WindowEvent
(the window state changed)
ContainerEvent
(a component has been added or removed)
Event Handling
User actions like clicking a button are modelled by an ActionEvent, and sent to
an ActionListener.
Window actions like clicking a close or minimize box are WindowEvents, sent
to WindowListeners.
Mouse actions like pressing the mouse is modelled in a MouseEvent, and is sent
to a MouseListener.
An Event object’s getSource() method returns a reference to the Component object that generated
the event.
Event Handling: Event Sources
A source must register listeners
Each of the event has its own registration method:
Syntax: <Source> . add<Type>Listener (handler);
Type is the name of event
Handler is reference to the event listener
Example:
addKeyListener()
addMouseMotionListener()
A source also provides a method to ‘unregister’ the listeners.
public void remove<type>Listener(handler);
Event Handling: Event Objects
Objects that represent a user action (e.g. mouse click) – contain detailed
information about the event.
When an event happens an event source sends an event object to its event
listeners
We are not going into details of EventObjects – we will need them only as
arguments to the method event performer in event listeners.
Event Handling: Event Listeners
Event listeners are objects that respond when an event occurs; or an object that wants
to be notified when an event has occured on a component.
Any object , whose class implements the XxxxListener interface, can be an event listener; The
common interface that all event listener interfaces must extend is EventListener.
ActionListener extends EventListener and is in the java.awt.event package, which is where all the AWT event classes
and listener interfaces are defined.
If the event listener has been added to an event source, the listener will be called when an
event occurs on that source.
Event Handling: Event Listeners
The javax.swing.event package contains the event classes and listener
interfaces unique to Swing.
The AWT components only generate AWT events, while Swing components
generate both AWT and Swing events.
For example, a Swing JButton is the source of java.awt.event.ActionEvent (an
AWT event class) and a javax.swing.event.ChangeEvent (a Swing event class).
Three Required Parts
Every event handler requires three pieces of code:
1. Declaration of the event handler(listener) class that implements a listener interface or extends a class that
someComponent.addXxxListener(instanceOfMyClass);
3. Providing code that implements the methods in the listener interface with in the event handler class
btnTest.addActionListener(lc);
if the Listener class is the class that contains the source object, then the reference
to the Listener object will be ‘this’
btnTest.addActionListener(this);
The Listener must implement the appropriate Listener interface and define
methods to receive and process notifications
Button(Action Listener)
To Listen and process the ActionEvent generated by the source button, the Listener class must
implement ActionListener interface
}
Text Field(Action Listener)
Text Field(Action Listener)
Item Event
(JCheckBox, JRadioButton, JComboBox)
Occurred by sources JCheckBox, JRadioButton, JComboBox.
JCheckBox and JRadioButton have two state SELECTED and
DESELECTED
Methods
(event object).getSource();//returns the source object
(event object).getStateChange() = = ItemEvent.SELECTED or
ItemEvent.DESELECTED
Listener interface that the Listener class must implement is ItemListener
Method that the Listener class should implement is
public void itemStateChange(ItemEvent ie);
JCheckBox(Action Listener)
• You may not want to be
alerted every time the user
selects or deselects a
checkbox.
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.
Class MouseEvent inherits several methods from class
InputEvent that can distinguish between mouse buttons.
isMetaDown() This method returns true when the user clicks the right mouse button
on a mouse with two or three buttons. To simulate a rightmouse-button click on a one-
button mouse, the user can press.
isAltDown() This method returns true when the user clicks the middle mouse button
on a mouse with three buttons. To simulate a middlemouse-button click on a one- or
two-button mouse, the user can press the Alt key on the keyboard and click the mouse
button.
Mouse Event Handling
the main thing you want to know about a MouseEvent is the location; that is,
where the mouse was clicked.
You can either request the x and y locations separately, or together as a
java.awt.Point object.
public int getX()
public int getY()
public Point getPoint()
Example
A mouse listener does not respond to mouse dragged or mouse moved events
because these are too common.
mouse moved and mouse dragged events are responded to by the
MouseMotionListener interface.
public interface MouseMotionListener extends EventListener
The MouseMotionListener interface declares these two methods that are missing
from MouseListener:
public abstract void mouseDragged(MouseEvent evt)
public abstract void mouseMoved(MouseEvent evt)
Example
To capture window events (such as when the user closes a window), you must have an object that
implements the WindowListener interface. The JFrame is the source of a WindowEvent.
e.g. WindowListener listener = …;
frame.addWindowListener(listener);
The WindowListener interface has seven distinct events that can happen. That means you must
override seven abstract methods.
An object that implements the WindowListener interfact must override these methods:
void windowOpened(WindowEvent e);
void windowClosing(WindowEvent e);
void windowClosed(WindowEvent e);
void windowIconified(WindowEvent e);
void windowDeiconified(WindowEvent e);
void windowActivated(WindowEvent e);
void windowDeactivated(WindowEvent e);
Example
Keyboard Event Handling
You can convert this into a localized string such as "END", "F4" or "Q" by
passing it to the static method, KeyEvent.getKeyText():
public static String getKeyText(int keyCode)
Generally you respond to key events directed at your component, by registering a
KeyListener object with the component.
The KeyListener interface defines the following methods, one for each type of
KeyEvent.
public abstract void keyTyped(KeyEvent evt)
public abstract void keyPressed(KeyEvent evt)
public abstract void keyReleased(KeyEvent evt)
Key Listener: Example
Key Codes
The KeyEvent class defines a little more than one hundred virtual key codes that
map to different, common, keyboard keys.
KeyEvent.VK_0 through KeyEvent.VK_9 are the same as ASCII '0' through '9'
(0x30 - 0x39)
KeyEvent.VK_A through KeyEvent.VK_Z are the same as ASCII 'A' through 'Z';
Funky Key Codes
KeyEvent.VK_F4, KeyEvent.VK_KANJI,
KeyEvent.VK_F5, KeyEvent.VK_LEFT,
KeyEvent.VK_F6, KeyEvent.VK_META,
KeyEvent.VK_F7, KeyEvent.VK_MODECHANGE,
KeyEvent.VK_MULTIPLY,
KeyEvent.VK_F8,
KeyEvent.VK_NONCONVERT,
KeyEvent.VK_F9, KeyEvent.VK_NUM_LOCK,
KeyEvent.VK_F10, KeyEvent.VK_F11, KeyEvent.VK_NUMPAD0,
KeyEvent.VK_F12, KeyEvent.VK_NUMPAD1,
KeyEvent.VK_FINAL, KeyEvent.VK_NUMPAD2,
KeyEvent.VK_HELP, KeyEvent.VK_NUMPAD3
KeyEvent.VK_HOME,
KeyEvent.VK_INSERT,
KeyEvent.VK_KANA,
Funky Key Codes
KeyEvent.VK_NUMPAD4, KeyEvent.VK_RIGHT,
KeyEvent.VK_NUMPAD5, KeyEvent.VK_SCROLL_LOCK,
KeyEvent.VK_NUMPAD6, KeyEvent.VK_SEMICOLON,
KeyEvent.VK_NUMPAD7, KeyEvent.VK_SEPARATER,
KeyEvent.VK_NUMPAD8,
KeyEvent.VK_SHIFT,
KeyEvent.VK_NUMPAD9,
KeyEvent.VK_OPEN_BRACKET, KeyEvent.VK_SLASH,
KeyEvent.VK_PAGE_DOWN, KeyEvent.VK_SPACE,
KeyEvent.VK_PAGE_UP, KeyEvent.VK_SUBTRACT,
KeyEvent.VK_PAUSE, KeyEvent.VK_TAB,
KeyEvent.VK_PERIOD, KeyEvent.VK_UNDEFINED,
KeyEvent.VK_PRINTSCREEN, KeyEvent.VK_UP
KeyEvent.VK_QUOTE,
Modifier Keys
The primary feature InputEvent adds the ability to test for additional conditions
on the event such as whether the ALT key was pressed at the same time as another
key, or whether the option key was held while the mouse was dragged.
The following four methods tell you whether or not the specified key was pressed
when this event was sent.
public boolean isShiftDown()
public boolean isControlDown()
public boolean isAltDown()
public boolean isMetaDown()
There is also a getWhen() method which returns the time the event occurred. This
is given as the number of milliseconds since midnight, January 1, 1970,
Greenwich Mean Time.
public long getWhen()
The java.util.Date and java.util.Calendar classes have methods you can use to
convert this to a date and time.
However, most of the time you'll only be concerned with differences in the time
between one event and another.
Mouse Button Modifiers
An InputEvent's modifiers are stored as an int value. Each bit in the int is a flag
corresponding to a particular modifier.
The corresponding values for these flags are given in the InputEvent class:
InputEvent.SHIFT_MASK
InputEvent.CTRL_MASK
InputEvent.ALT_MASK
You can retrieve the modifiers for an event with the getModifiers() method:
public int getModifiers()
Use the bitwise & operator to test whether a particular flag is set.
if (evt.getModifiers() & InputEvent.SHIFT_MASK != 0) {
System.out.println(“SHIFT was pressed");
}
Adapter Classes
To make it easier for programmers, the designers of Java supplied adapter classes.
Each AWT listener interface with more than one method comes with a companion
adapter class.
These adapter classes implement all the methods in the interface but does nothing with
them.
This means that the adapter classes satisfy all the technical requirements for
implementing the listener interface.
You can then just extend your class from these adapter classes if you don’t need to
extend it from anything else.
The programmer can extend the adapter class to inherit the default
implementation of every method, then override the method(s) needed for event
handling.
Adapter Classes
The adapter class for the WindowListener interface is WindowAdapter. You can use it like
this:
class Terminator extends WindowAdapter {…}
Creating a listener class that extends the WindowAdapter is even easier than that. There is
no need to give a name to the listener object.
frame.addWindowListener(new Terminator());
You can go even further by using an anonymous inner class:
frame.addWindowListener(new
WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0)
}
});
Have you observed the code?.
Adapter Classes
import java.awt.*; Without extending the MouseAdapter class, I would have had to
write the same class like this:
import java.awt.event.*;
import java.awt.*;
public class MouseBeeper extends MouseAdapter {
import java.awt.event.*;
public void mouseClicked(MouseEvent evt) {
public class MouseBeeper implements MouseListener {
Toolkit.getDefaultToolkit().beep();
public void mouseClicked(MouseEvent evt) {
}
Toolkit.getDefaultToolkit().beep();
}
}
You do not need to use the adapter classes if you don't want to.
Menu
A menu provides a space-saving way to let the user choose one of several options.
Menus are unique in that, by convention, they aren't placed with the other components
in the UI.
Instead, a menu usually appears either in a menu bar or as a popup menu.
Menus are composed of three hierarchical pieces.
MenuBar, Menu and MenuItem
The menu bar contains the various menus.
Each menu bar contains one or more menus.
Each menu contains one or more menu items.
The menu items are the individual actions such as Open, Print, Cut or Copy.
They are not shown except when the menu is active.
No more than one menu will be active at a time.
Menu
You can set colors for GUI components by using the java.awt.Color class.
Colors are made of red, green, and blue components, each of which is represented by
a byte value that describes its intensity, ranging from 0 (darkest shade) to 255
(lightest shade).
Example:
Color c = new Color(228, 100, 255);
Color Setting: Standard Colors
Thirteen standard colors (black, blue, cyan, darkGray, gray, green, lightGray,
magenta, orange, pink, red, white, yellow) are defined as constants in java.awt.Color.
The standard color names are constants, but they are named as variables with
lowercase for the first word and uppercase for the first letters of subsequent words.
Thus the color names violate the Java naming convention. Since JDK 1.4, you can
also use the new constants: BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN,
LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE, and YELLOW.
Color Setting
You can use the following methods to set the component’s background and foreground colors
(There are thirteen standard color names):
setBackground(Color c)
setForeground(Color c)
Example:
jbt.setBackground(Color.yellow);
jbt.setForeground(Color.red);
If for some reason, the selections built into the Color object do not fit your needs, you can create
your own color using one of over 16 million different combinations.
Color myColor = new Color(redValue, greenValue, blueValue);
Color Chooser
f=new Jframe();
UIManager.setLookAndFeel("javax.swing
.plaf.metal.MetalLookAndFeel");
UIManager.setLookAndFeel("com.sun.jav
a.swing.plaf.windows.WindowsLookAnd
Feel");
UIManager.setLookAndFeel("javax.swing
.plaf.nimbus.NimbusLookAndFeel");
UIManager.setLookAndFeel("com.sun.jav
a.swing.plaf.motif.MotifLookAndFeel");
Set Frame Icon
Beep
Toolkit.getDefaultToolkit().beep();
Get Print Job
Toolkit.getDefaultToolkit() .getPrintJob(null, null, new Properties());
Swing is HUGE! You must explore it
further…
} CHAPTER 3