410 likes | 720 Views
Graphical User Interface(GUI). Objectives. GUI Container classes Layout managers Flow, Border, Grid layouts. Graphical User Interface: Introduction.
E N D
Objectives • GUI Container classes • Layout managers • Flow, Border, Grid layouts
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
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
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
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
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.swingpackage to use Swing components.
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
An initial AWT Program: Try It import java.awt.*; //GuiFrame.java public 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
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
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 theGuiFrame.javaexample to incorporate event handling
A Frame with Window Event handler import java.awt.*; // FrameWithExit.java import java.awt.event.*; // Events public 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 This class is closable Registering the WindowListener with the class These 7 methods are the event handlers for Window events, defined in the WindowListener interface windowClosing is the only method implemented, provides the capability to close a window
A closable application import java.awt.*; //GuiFrameClosable.java public 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
An initial Swing Program import javax.swing.*; //SwingFrame.java import 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
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
Heavy weight and Light weight Components • Heavy weight or top-level components are JFrame, JApplet, JDialog, JWindow • Light weight components are many and are subclasses of JComponent • JPanel • JList • JLabel • JToolTip • AbstractButton - JButton, JToggleButton, JMenuItem • JMenuBar
JFrame • Unless it is an applet, an application uses JFrame as the top level component • The inheritance hierarchy of a JFrame java.lang.Object java.awt.Component java.awt.Container java.awt.Window java.awt.Frame javax.swing.JFrame AWT Classes
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();
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
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 manager JFrame jf = new JFrame(); Container cp = jf.getContentPane(); JPanel jp = new JPanel(); cp.add(jp, BorderLayout.WEST);
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
JButton • JButton provides 4 constructors JButton() - No text or icon JButton(Icon icon) - Button with an icon face JButton(String text) - Button with a text face JButton(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
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
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
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 West Center East South
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());
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
GuiWithBorderLayout.java • Output from the program
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 Example: GuiWithBorderLayout.java
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
FlowLayout Object • Create a FlowLayout object FlowLayout fl = new FlowLayout(); // defaults are used • Align components on the left side of the row FlowLayout 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 components FlowLayout fl = new FlowLayout(FlowLayout.RIGHT,2,3); • As in the case of BorderLayout, we can create FlowLayout object anonymously
GuiWithFlowLayout.java • Output from 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 Panel jp = 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(); } } Example: GuiWithFlowLayout.java
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
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
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);
GuiWithGridLayout.java • Output from GuiWithGridLayout
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 Panel jp = new JPanel(); jp.setBackground(Color.blue); jp.setLayout(new GridLayout(4,4,1,1)); // create the buttons and add them to the panel gridBtns = 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 frame jl = 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(); } } Example: GuiWithGridLayout.java
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
Exercise • We will create a minimal calculator which looks like the following Use a JLabel to display messages Other items are JButtons