GUI Design
GUI Design
Programs which use graphical user interfaces are event driven programs, in contrast to procedure-based programs.- Procedure-based programming: Control resides with the running program. I/O occurs at the request of the running program.
- Event-driven programming: Control resides with the interactive user. The program responds to spontaneous I/O events.
Programmer's responsibilities:
- Defining GUI components.
- Arranging the components in a window or frame.
- Connecting components to program actions.
Packages
- java.awt
- Abstract Windowing Toolkit
- Original GUI package
- "heavyweight" components
- javax.swing Updated GUI package
- "lightweight" components
- uses awt event model
- java.awt.event
- event-handling classes
Components
- Swing components can be classified as top-level, intermediate-level, and low-level.
Top-level components
- JFrame the topmost window of an application
- JApplet Applets are created by extending JApplet.
- JDialog A popup window or message box used as a temporary I/O window
Middle-level components
- JPanel
- A blank area in a window
- Acts as both a component and a container
- Used to create the containment hierarchy of an application or applet
Low-level (atomic) components
- JLabel
- JTextArea
- JButton
- JRadioButton
- JCheckBox
- JList
- JMenu
- JComboBox
- JScrollBar
- JScrollPane
example A minimal GUI application can be constructed by creating a frame and making it visible:
import javax.swing.*;
class GUITest {
JFrame frame = new JFrame("GUI Test");
GUITest(){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,300);
frame.setVisible(true);
}
static public void main(String[] args){
new GUITest();
}
}
Constructing a GUI
To construct a GUI, the programmer must create a group of components and arrange them in a containment hierarchy. Every component (except the top-level components) must be placed in some java.awt.Container.Each of the top-level components possesses a container called its content pane. Every component in the top-level component must be placed in its content pane, or in some container nested within its content pane. The root of the containment hierarchy is the content pane of a JFrame or JApplet.
For each component,
- Instantiate the component.
- Customize it by setting properties, such as background color, font, minimum size, etc.
- Add it to a container.
- Instantiate the container.
- Customize it by setting properties.
- Choose its layout manager (or else use the default layout manager).
- Add it to a container.
-
example A GUI application with two JLabels placed in two
JPanels:
import javax.swing.*;
class GUITest {
JFrame frame = new JFrame("GUI Test"); JPanel top = new JPanel();
JPanel bottom = new JPanel);
JLabel hello = new JLabel("Hello,");
JLabel world = new JLabel("world");
GUITest(){
top.add(hello);
bottom.add(world);
frame.getContentPane().add(top);
frame.getContentPane().add(bottom);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,300);
frame.setVisible(true);
}
static public void main(String[] args){
new GUITest();
}
}
Layout Managers
- Each Container has a layout manager, whose job it is to arrange the components visually within the container.
- The user does not specify exact pixel locations for components.
- Instead, the user selects a LayoutManager which follows general guidelines for placing components.
- Hints may be given to the LayoutManager, such as a preferred size for a component, but the LayoutManager need not obey them.
- When a component is added to a container, the user may specify a constraint object which may be used by the LayoutManager. For example, BorderLayout recognizes the constraints BorderLayout.NORTH, BorderLayout.SOUTH, BorderLayout.CENTER, BorderLayout.WEST, and BorderLayout.EAST.
The user still has a great deal of control by
- structuring the containment hierarchy
- choosing the layout manager of each container
- specifying component attributes
- passing constraints to the layout manager
- FlowLayout
- Most basic layout manager
- Components placed left to right in order added
- When edge of container reached, continues on next line
- Components can be left-aligned, centered (default), or right-aligned
- BorderLayout
- Default manager for content pane
- Arrange components into 5 regions
- North, south, east, west, center
- Up to 5 components can be added directly, one for each region
- Components placed in
- North/South - Region is as tall as component
- East/West - Region is as wide as component
- Center - Region expands to take all remaining space
- BoxLayout
- Components are laid out vertically or horizontally
- Full-featured flow layout
- Use RigidArea or Glue as filler to help arrange components
- GridLayout
- Divides container into a rectangular grid
- Components placed in rows and columns
- All components have same width and height
- Added starting from top left, then from left to right
- When row full, continues on next row, left to right
- CardLayout
- GridBagLayout
Event Handling
Events in a GUI are actions such as a timer ticking or a user typing a character, moving a mouse, or pushing a mouse button. GUI programs are designed to operate in response to events.Java AWT event handling is based on the principle of delegation. Responsibility for handling events for a particular GUI component is delegated to an event handler ("listener") object. The listener is responsible for responding to events which are associated with that component. This model is an example of the Observer-Observable design pattern.
To write code for a particular event, say a user entering a word in a text field, the user must
- Write code for an event handler class. The event handler class will contain methods to respond to one or more events.
- Create an instance of the class.
- Register the listener object with the component.
example Create a text field and give it an action listener. (The code to add the name field to a container is not given here.)
JTextField nameField = new JTextField();
String name;
nameField.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
name = nameField.getText();
}
}
);
All events are subclasses of java.awt.AWTEvent. All listeners are subinterfaces of java.util.EventListener. Here is a summary of events and listeners used in GUI programs:
| Event Class |
Listener Interface |
Listener Methods |
| ActionEvent |
ActionListener |
actionPerformed |
| WindowEvent |
WindowListener |
windowClosing windowOpened windowIconified windowDeiconified windowClosed windowActivated windowDeactivated |
| ContainerEvent |
ContainerListener |
componentAdded componentRemoved |
| ComponentEvent |
ComponentListener |
componentMoved componentHidden componentResized componentShown |
| FocusEvent |
FocusListener |
focusGained focusLost |
| TextEvent |
TextListener |
textValueChanged |
| KeyEvent |
KeyListener |
keyPressed keyReleased keyTyped |
| MouseEvent |
MouseListener |
mousePressed mouseReleased mouseEntered mouseExited mouseClicked |
| MouseMotionListener |
mouseDragged mouseMoved |
Painting
You can draw a picture on any JComponent. To do so, override
the component's paintComponent method, adding your own calls to drawing
methods. Here's an example:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class GraphicsTest {
class MyPanel extends JPanel {
public void paintComponent(Graphics g){
super.paintComponent(g);
GraphicsTest.this.drawOnPanel(g);
}
}
JFrame frame = new JFrame("GUI Test");
JPanel panel = new MyPanel();
GraphicsTest(){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,300);
Container c = frame.getContentPane();
c.add(panel);
frame.setVisible(true);
}
void drawOnPanel(Graphics g){
g.drawOval(10, 20, 30, 40);
}
static public void main(String[] args){
new GraphicsTest();
}
}