Download - Graphical User Interface(GUI)
Gui-1for IST410 Students only
Graphical User Interface(GUI)
Gui-2for IST410 Students only
Objectives
GUI Container classes Layout managers Flow, Border, Grid layouts
Gui-3for IST410 Students only
Graphical User Interface: Introduction
Up to this point, we have written programs where our interaction was limited to taking inputs from the command line and writing output to the shell window
Most modern programs do not work that way; they allow users to take inputs from the screen and display result back to the screen
Such programs are generally called event driven programs
Event driven programs use GUI objects such as buttons, lists, text fields to facilitate user interaction
Gui-4for IST410 Students only
Graphical User Interface: Introduction
Event driven programs use two different sets of objects: one to paint the user interface components on the display screen, and the other to handle or respond to events
Events are user interaction with a program: a mouse click, a key stroke, selection of a menu choice
For example, when a mouse click occurs on a Button, it is an action event i.e. the program is expected to take ‘some’ action
The user interface components are defined in graphics packages of Java: AWT and Swing
Gui-5for IST410 Students only
Graphical User Interface: Introduction
General strategy to write an event driven program Define a container object Place appropriate GUI components on the container object Register listeners with GUI objects to listen for events; Define event handlers
Listeners are interfaces whose method(s) are invoked by the JVM when an event occurs
The response of the program is coded within these methods - hence event handlers
In this section, we explore the mechanics of constructing GUI interfaces
for IST410 Students only Gui-6
Swing
Swing is a set of customizable graphical toolkit that can be used in developing an enterprise level application
It is a part of a larger suite of libraries known as JFC - Java Foundation Class
JFC includes 2 graphics component libraries AWT - Abstract Window Toolkit Swing
JFC also includes other libraries to support graphics oriented programming
Gui-7for IST410 Students only
AWT and Swing
AWT is the graphical toolkit in all of jdk1.x series AWT was the GUI toolkit of choice before the release of
Swing classes Swing is not a replacement of AWT, but is built on top of
core AWT classes Swing can be used with jdk1.1.5 or later versions, and is a
component of the core java in jdk1.2 and jdk1.3 A program can mix both AWT and Swing components A program must import the java.awt package to use AWT
components and javax.swing package to use Swing components.
Gui-8for IST410 Students only
AWT
AWT package comprises a number of classes Layout classes: BorderLayout, FlowLayout,
GridLayout, CardLayout, GridBagLayout Graphics classes - Color, Dimension, Font, Image, etc. Toolkit Component classes - Button, Checkbox, Choice, Label,
and others Container classes - Panel, Window, Frame, Applet MenuComponent - MenuBar, MenuItem, Menu etc
Gui-9for IST410 Students only
An initial AWT Program: Try It
import java.awt.*; //GuiFrame.javapublic class GuiFrame extends Frame {
public GuiFrame() {}public GuiFrame(String s){
super(s);}public static void main(String[] args) {
GuiFrame gf = new GuiFrame("Hello Java Frame");gf.setBackground(Color.red);gf.setSize(300,300);gf.setVisible(true);
}}
All applications (not applets) need a background - a Frame
Title string of the frame
The frame becomes visible here, usually the last logical statement
Gui-10for IST410 Students only
Discussion of GuiFrame.java
An application starts with defining a background surface: a Frame in AWT
Components are then added on to the Frame - none in this example
Placement of the components are left to Layout Managers Background color is set to Red using Color.red, a
predefined color in the Color class of AWT The size of the Frame is set to 300,300 pixels The frame is finally made visible There is no event handler in this program and therefore,
we cannot interact with this program
Gui-11for IST410 Students only
Closing an Application
In order to close the frame, we need to incorporate an event handler
There are different type of event handlers in Java; we need the Window Event handler.
Window event handler is registered through the window event interface known as WindowListener
We discuss the event handling mechanism in the next chapter
We do incorporate one event handler in our examples enabling us to close them
Let us modify the GuiFrame.java example to incorporate event handling
Gui-12for IST410 Students only
A Frame with Window Event handler
import java.awt.*; // FrameWithExit.java import java.awt.event.*; // Eventspublic class FrameWithExit extends Frame implements WindowListener { public FrameWithExit() { super(); addWindowListener(this); } public FrameWithExit(String s) { super(s); addWindowListener(this); } public void windowClosed(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) { System.exit(0); }} // end FrameWithExit class
These 7 methods are the event handlers for Window events, defined in the WindowListener interface
Registering the WindowListener with the class
windowClosing is the only method implemented, provides the capability to close a window
This class is closable
Gui-13for IST410 Students only
A closable application
import java.awt.*; //GuiFrameClosable.javapublic class GuiFrameClosable extends FrameWithExit {
public GuiFrameClosable() {}public GuiFrameClosable(String s){ super(s);}public static void main(String[] args) { GuiFrameClosable gf = new GuiFrameClosable("GUI Closable Frame"); gf.setBackground(Color.red); gf.setSize(300,300); gf.setVisible(true);}
}
This class is closable since it extends a Frame with an event handler
Gui-14for IST410 Students only
An initial Swing Program
import javax.swing.*; //SwingFrame.javaimport java.awt.Color;public class SwingFrame extends SwingFrameWithExit {
public SwingFrame() {}public SwingFrame(String s){
super(s);}public static void main(String[] args) {
SwingFrame gf = new SwingFrame("Swing Closable Frame");gf.getContentPane().setBackground(Color.red);gf.setSize(300,300);gf.setVisible(true);
}}
This is almost exactly same as FrameWithExit except it extends JFrame
We use the ContentPane of a JFrame; we do not directly place components on a JFrame
Gui-15for IST410 Students only
Component layering in a Graphical Interface
A graphical interfce is built using a top-level component, sometimes referred as heavy weight components
Graphical widgets such as Buttons, Combo boxes are placed on heavy weight components
These widgets are sometimes referred as light weight components
Heavy weight components provide the background that are opaque and interact with the underlying operating system
Light weight components are painted on this opaque background and do not depend on the underlying system
Gui-16for IST410 Students only
Heavy weight and Light weight Components
Heavy weight or top-level components areJFrame, JApplet, JDialog, JWindow
Light weight components are many and are subclasses of JComponent
JPanel JList JLabel JToolTip AbstractButton - JButton, JToggleButton, JMenuItem JMenuBar
Gui-17for IST410 Students only
JFrame
Unless it is an applet, an application uses JFrame as the top level component
The inheritance hierarchy of a JFramejava.lang.Object java.awt.Component
java.awt.Container java.awt.Window
java.awt.Frame javax.swing.JFrame
AWT Classes
Gui-18for IST410 Students only
JFrame
An application creates a window by instantiating a frame i.e. JFrame
JFrame can be thought of as a complete data structure on which light weight components are painted
JFrame (also Frame) comes with built in controls such as minimize, maximize and close buttons, however, event handlers are still needed to make these buttons functional
Components cannot be directly placed on a JFrame, but a layer of a JFrame known as ContentPane
JFrame jf = new JFrame();Container cp = jf.getContentPane();
Gui-19for IST410 Students only
JPanel
JPanels are also containers Unlike JFrames, JPanels can be nested as well placed in a
JFrame JFrames cannot be nested nor can be placed in another
container The inheritance hierarchy
java.lang.Object java.awt.Component
java.awt.Container javax.swing.JComponent
javax.swing.JPanel
Gui-20for IST410 Students only
JPanel
Components can be added to JPanels Since JPanels can be nested, complex layouts can be
constructed by assigning different layouts to different panels
add method is used to place a component on a container The location of the placement is determined by the layout
managerJFrame jf = new JFrame();Container cp = jf.getContentPane();JPanel jp = new JPanel();cp.add(jp, BorderLayout.WEST);
Gui-21for IST410 Students only
JButton
We use button objects for most of our examples to demonstrate principles of component placement and event handling
We, therefore, discuss JButton, the button object of Swing class a bit out of turn
JButton is a subclas of AbstractButton, which in turn is derived from JComponent
JButton is a light weight component and needs to be placed in some container such as a panel or a frame to become visible
JButtons, unlike its AWT cousin(Button), can be created with a text and/or picture face
Gui-22for IST410 Students only
JButton
JButton provides 4 constructorsJButton() - No text or iconJButton(Icon icon) - Button with an icon faceJButton(String text) - Button with a text faceJButton(String text, Icon icon) - Button with both icon and
text face Icon is an interface and is implemented by, among others,
ImageIcon class in Swing We can use ImageIcon class to translate graphics files such
as gif files to ImageIcon objects These icon objects can then be used to paint the face of a
JButton as well as many other swing components
Gui-23for IST410 Students only
Layout Managers
Layout of a container is controlled by a class of objects called Layout managers
Swing inherits several layout managers from AWT, and also adds new ones
These layout managers decide the placement of components in the container
They are also responsible for repainting windows and containers when the user resizes the frame, or the application is moved to a machine with a different resolution, or to a different machine
Gui-24for IST410 Students only
Layout Managers
A program can, of course, turn off the layout managers If layout managers are not used, it is the program’s
responsibility to locate each component, as well as manage resizing and repainting
Several layout managers are discussed in this section BorderLayout Other available layouts FlowLayout GridBagLayout GridLayout CardLayout
BoxLayout Except for BoxLayout, all others are available in AWT
Gui-25for IST410 Students only
BorderLayout Manager
A BorderLayout divides the container into 5 regions
JFrame and Frame(AWT) use BorderLayout as their default layout managers
To assign Border layout to panels, one has to construct a BorderLayout object
North
South
CenterWest East
Gui-26for IST410 Students only
BorderLayout Object
A BorderLayout object can be constructed by calling the constructor of the layout manager
BorderLayout bl = new BorderLayout();cp.setLayout(bl); // set the layout of cp to bl
cp can be a Frame, the content pane of a JFrame, Panel, or a JPanel
It is necessary to create a named layout object only if the program is going to make a reference to such an object
Otherwise, the layout manager can be created and assigned anonymously
cp.setLayout(new BorderLayout());
Gui-27for IST410 Students only
BorderLayout Object
BorderLayout class provides a second constructor through which horizontal and vertical gaps among components can be specified
BorderLayout bl = new BorderLayout(10,10); The integers 10,10 define horizontal and vertical gaps
respectively among components placed in the container
Gui-28for IST410 Students only
GuiWithBorderLayout.java
Output from the program
Gui-29for IST410 Students only
Example: GuiWithBorderLayout.java
import javax.swing.*;import java.awt.*;import java.awt.event.*;public class GuiWithBorderLayout extends
SwingFrameWithExit { Container cp; JButton left, right, top, bottom, center;
public GuiWithBorderLayout() { cp = getContentPane(); cp.setLayout(new BorderLayout(10,10)); cp.setBackground(Color.red); left = new JButton("Left"); cp.add(left,BorderLayout.WEST); right = new JButton("Right"); cp.add(right,BorderLayout.EAST); center = new JButton("Center");
cp.add(center,BorderLayout.CENTER); top = new JButton("Top"); cp.add(top,BorderLayout.NORTH); bottom = new JButton("Bottom"); cp.add(bottom,BorderLayout.SOUTH); setSize(300,300); setVisible(true); }
public static void main(String[] args) { GuiWithBorderLayout gbl = new
GuiWithBorderLayout(); }}
We use JButtons to fill in regions of the JFrame
Gui-30for IST410 Students only
FlowLayout Manager
Panels and JPanels use Flow layout as their default manager
FlowLayout objects are needed for Frames and JFrames In FlowLayout, components are added left to right in the
order they are inserted into the container When one row is completed, next insert automatically
flows into the next row Components are centered in a row by default Components can be aligned left or right by using an
overloaded version of the layout manager’s constructor
Gui-31for IST410 Students only
FlowLayout Object
Create a FlowLayout objectFlowLayout fl = new FlowLayout(); // defaults are used
Align components on the left side of the rowFlowLayout fl = new FlowLayout(FlowLayout.LEFT);
Align components to the right side of the row, use a horizontal gap of 2 pixels, and a vertical gap of 3 pixels among componentsFlowLayout fl = new FlowLayout(FlowLayout.RIGHT,2,3);
As in the case of BorderLayout, we can create FlowLayout object anonymously
Gui-32for IST410 Students only
GuiWithFlowLayout.java
Output from GuiWithFlowLayout.java
Gui-33for IST410 Students only
Example: GuiWithFlowLayout.java
import javax.swing.*;import java.awt.*;import java.awt.event.*;public class GuiWithFlowLayout { SwingFrameWithExit jf; Container cp; JButton one, two, three; JButton exit; JPanel jp; public GuiWithFlowLayout() { ImageIcon bullet = new ImageIcon("bullet2.gif"); ImageIcon middle = new ImageIcon("middle.gif");
jf = new SwingFrameWithExit();cp = jf.getContentPane();cp.setLayout(new BorderLayout(2,2));cp.setBackground(Color.red);// create the Paneljp = new JPanel();jp.setBackground(Color.blue);
// create the buttons and add to the panel one = new JButton("ONE",bullet); jp.add(one); two = new JButton(middle); jp.add(two); three = new JButton("THREE",bullet); jp.add(three); cp.add(jp,BorderLayout.CENTER);
// add panel to the frame exit = new JButton("EXIT"); cp.add(exit,BorderLayout.SOUTH); jf.setSize(300,300); jf.setVisible(true);
} public static void main(String[] args) { GuiWithFlowLayout gbl = new GuiWithFlowLayout(); }}
Gui-34for IST410 Students only
Discussion: GuiWithFlowLayout.java
We use an object of type SwingFrameWithExit instead of a JFrame; this works correctly since the class SwingFrameWithExit not only extends JFrame but also has an event handler associated with it.
Several JButtons are created using Icon option of the constructor
A JPanel object is placed in the JFrame object; JFrame has BorderLayout and JPanel has FlowLayout
Notice the usage of the add method. It is used to add JPanel to the JFrame, as well as JButtons to JPanel and JFrame
Gui-35for IST410 Students only
GridLayout Manager
GridLayout enables a program to divide a container into a grid For example a 3,4 grid: Not a default layout manager
for any container type Creating a layout object
GridLayout gl = new GridLayout(3,4);cp.setLayout(gl); // cp is a JPanel, Panel, Frame, JFrame
Components are added left to right, top to bottom in the order of insertion
Gui-36for IST410 Students only
GridLayout Object
As before, there are multiple constructors available Default: One column per component, in a single row
GridLayout gl = new GridLayout(); Specify number of rows and column
GridLayout gl = new GridLayout(3,4); Specify grid size as well as horizontal and vertical gaps
GridLayout gl = new GridLayout(3,4,2,2);
Gui-37for IST410 Students only
GuiWithGridLayout.java
Output from GuiWithGridLayout
Gui-38for IST410 Students only
Example: GuiWithGridLayout.java
import javax.swing.*;import java.awt.*;import java.awt.event.*;public class GuiWithGridLayout {
private SwingFrameWithExit jf;private Container cp;private JButton[] gridBtns;private JLabel jl;private JPanel jp;private ImageIcon im;
public GuiWithGridLayout() { im = new ImageIcon("middle.gif");
} public void build() { jf = new SwingFrameWithExit();
jf.setTitle("Grid Layout Test");cp = jf.getContentPane();cp.setLayout(new BorderLayout(1,1));
cp.setBackground(Color.red);// create the Paneljp = new JPanel();
jp.setBackground(Color.blue);jp.setLayout(new GridLayout(4,4,1,1));// create the buttons and add them to the panelgridBtns = new JButton[16];for (int i = 0; i< 16; i++){ gridBtns[i] = new JButton(im); jp.add(gridBtns[i]);}cp.add(jp,BorderLayout.CENTER);
// add panel to the framejl = new JLabel("Border Layout JFrame",SwingConstants.RIGHT);cp.add(jl,BorderLayout.NORTH);jf.setSize(300,300);jf.setVisible(true);
} public static void main(String[] args) { GuiWithGridLayout gl = new GuiWithGridLayout();
gl.build(); }}
Gui-39for IST410 Students only
Discussion: GuiWithGridLayout.java
We use SwingFrameWithExit in place of an ordinary JFrame
We use an array of JButton objects; instantiation and handling of these buttons are no different than ordinary JButtons
Since GridLayout is not the default layout of any container class, an anonymous GridLayout object is created and assigned as the layout manager of the JPanel
We also use JLabel, a passive Swing component, to display text as well as image
Gui-40for IST410 Students only
Exercise
We will create a minimal calculator which looks like the following
1 2 3 +4 5 6 -7 8 9 *0 C = /
Use a JLabel to display messages
Other items are JButtons