L03. Graphical User Interface Part 1
L03. Graphical User Interface Part 1
Bonus Slides
BJP book
Graphical User Interfaces
Graphical input and output with
JOptionPane
• An option pane is a simple dialog box for graphical input/output
• JOptionPane : Java class used to show option panes
– belongs to javax.swing package.
• Useful methods of JOptionPane
– showMessageDialog(<parent>, <message>)
Displays a message on a dialog with an OK button.
– showInputDialog(<parent>, <message>)
Displays a message and textfield for input; returns
the user's value entered as a String.
• can pass null for the parent to all methods
– showConfirmDialog(<parent>, <message>)
Displays a message and list of choices Yes, No, Cancel;
returns user's choice as an int with one
of the following values:
• JOptionPane.YES_OPTION
• JOptionPane.NO_OPTION
• JOptionPane.CANCEL_OPTION
• can pass null for the parent to all methods
2
JOptionPane.showMessageDialog()
• showMessageDialog analogous to System.out.println to display a message
import javax.swing.*;
public class MessageDialogExample {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null,"How's the weather?");
JOptionPane.showMessageDialog(null, "Second message");
}
}
3
JOptionPane.showConfirmDialog()
• showConfirmDialog analogous to a System.out.print that prints a question,
then reading an input value from the user (can only be one of the provided choices)
import javax.swing.*;
public class ConfirmDialogExample {
public static void main(String[] args) {
int choice = JOptionPane.showConfirmDialog(null,
"Erase your hard disk?");
if (choice == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(null, "Disk erased!");
} else {
JOptionPane.showMessageDialog(null, "Cancelled.");
}
}
}
4
JOptionPane.showInputDialog()
• showInputDialog analogous to a System.out.print that prints a
question, then reading an input value from the user (can be any value)
import javax.swing.*;
public class InputDialogExample {
public static void main(String[] args) {
String name = JOptionPane.showInputDialog(null,
"What's yer name, pardner?");
JOptionPane.showMessageDialog(null, "Yeehaw, " + name);
}
}
5
Working with Frames
Onscreen GUI elements
• Most GUIs are not composed of option panes; they are too limited. Instead,
complex GUIs contain the following elements:
6
JFrame example 1
• A simple program that creates and shows a JFrame:
import javax.swing.*;
public class SimpleFrame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setVisible(true);
}
}
• Graphical output:
7
JFrame example 2
import java.awt.*;
import javax.swing.*;
public class SimpleFrame2 {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setForeground(Color.WHITE);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.setLocation(new Point(10, 50));
frame.setSize(new Dimension(300, 120));
frame.setTitle("A frame");
frame.setVisible(true);
}
}
• Graphical output:
8
JFrame properties
• JFrames have the following properties that you can get/set:
name type description methods
default close int what should happen when getDefaultCloseOperation,
setDefaultCloseOperation
operation frame is closed
9
Useful Properties of all
Components including JFrame
name type description methods
background Color background color getBackground,
setBackground
enabled boolean whether the component can be isEnabled, setEnabled
interacted with
font Font font used to display any text getFont, setFont
on the component
foreground Color foreground color getForeground,
setForeground
location Point (x, y) position of component getLocation,
on screen setLocation
size Dimension width, height of component getSize, setSize
10
Java GUI: AWT and Swing
• When doing GUI programming, always import these packages:
import java.awt.*;
import javax.swing.*;
• Sun's initial idea: create a set of classes/methods that can be used to
write a multi-platform GUI (Abstract Windowing Toolkit, or AWT)
– problem: not powerful enough; limited; a bit clunky to use
• Second edition (JDK v1.2): Swing
– a newer library written from the ground up that allows much more
powerful graphics and GUI construction
• Drawback: Both exist in Java now; easy to get them mixed up; still
have to use both sometimes!
11
JFrame
frame is a graphical window that can be used to hold other components
• public JFrame()
public JFrame(String title)
– Creates a frame with an optional title.
• public void setTitle(String text)
– Puts the given text in the frame’s title bar.
• public void setDefaultCloseOperation(int op)
– Makes the frame perform the given action when it closes.
– Common value: JFrame.EXIT_ON_CLOSE
• public void add(Component comp)
– Places the given component or container inside the frame.
• How would we add more than one component to the frame?
• NOTE: Call setVisible(true) to make a frame appear on screen after creating it.
12
JButton, JLabel
The most common component—
a button is a clickable onscreen
region that the user interacts with
to perform a single command
14
Components example
• This program attempts to show 2 buttons:
import java.awt.*;
import javax.swing.*;
17
Changing
import javax.swing.*;
import java.awt.*;
public class MessageDialogExample {
layouts
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300, 100));
frame.setTitle("A frame");
JButton button1 = new JButton();
button1.setText("I'm a button.");
button1.setBackground(Color.BLUE);
frame.add(button1);
JButton button2 = new JButton();
button2.setText("Click me!");
button2.setBackground(Color.RED);
frame.add(button2);
frame.setLayout(new FlowLayout());
frame.pack();
frame.setVisible(true);
}
}
18
Event-driven
programming
• program's execution is indeterminate
• on-screen components cause events to occur when they are clicked /
interacted with
• events can be handled, causing the program to respond, driving the
execution thru events (an "event-driven" program)
• import java.awt.event.*;
19
Listening for events
• Action events: ActionEvent
– most common / simple event type in Swing
– events represent an action occurring on a GUI component
– created by:
• button clicks, check box checking / unchecking, menu clicks, pressing Enter in a text
field, etc.
• attach a listener to the component
21
Attaching an
public class Myclass {
ActionListener
public static void main(String[] args) { import javax.swing.*;
JFrame frame = new JFrame(); import java.awt.*;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); import java.awt.event.*;
frame.setSize(new Dimension(300, 100));
frame.setTitle("A frame");
frame.add(button1);
frame.setLayout(new FlowLayout());
frame.pack();
frame.setVisible(true);
}
}
22
Laying out components
How does the programmer specify where each component sits in the
window, how big each component should be, and what the
component should do if the window is resized/moved/maximized/etc?
23
Layout managers
• Here are several common Java layout managers:
24
Containers
• container: An object that holds components; it also governs their
positions, sizes, and resizing behavior.
• Containers have the following public methods:
– public void add(Component comp)
public void add(Component comp, Object info)
Adds a component to the container, possibly giving extra information about
where to place it.
– public void remove(Component comp)
Removes the given component from the container.
– public void setLayout(LayoutManager mgr)
Uses the given layout manager to position the components in the container.
– public void validate()
You should call this if you change the contents of a container that is already on
the screen, to make it re-do its layout.
25
JPanel
• A panel is our container of choice; it provides the methods from the
previous slide and defines these additional methods (among others):
– public JPanel()
Constructs a panel with a default flow layout.
26
Preferred size
• Swing component objects each have a certain size they would "like"
to be--just large enough to fit their contents (text, icons, etc.)
• This is called the preferred size of the component
• 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
27
FlowLayout
public FlowLayout()
28
FlowLayout example
import java.awt.*;
import javax.swing.*;
public class FlowLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(320, 75));
frame.setTitle("Flow layout");
frame.setLayout(new FlowLayout());
frame.add(new JLabel("Type your ZIP Code: "));
frame.add(new JTextField(5));
frame.add(new JButton("Submit"));
frame.setVisible(true);
}
}
29
GridLayout
public GridLayout(int rows, int columns)
30
GridLayout example
import java.awt.*;
import javax.swing.*;
public class GridLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300, 120));
frame.setTitle("The grid");
// 2 rows, 3 columns
frame.setLayout(new GridLayout(2, 3));
for (int i = 1; i <= 6; i++) {
JButton button = new JButton();
button.setText("Button " + i);
frame.add(button);
}
frame.setVisible(true);
}
}
31
BorderLayout
public BorderLayout()
divides container into five regions: NORTH, SOUTH, WEST, EAST,
CENTER
– NORTH and SOUTH regions expand to fill region horizontally, and use
preferred size vertically
– WEST and EAST regions expand to fill region vertically, and use preferred size
horizontally
– CENTER uses all space not occupied by others
32
BorderLayout example
import java.awt.*;
import javax.swing.*;
public class BorderLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(210, 200));
frame.setTitle("Run for the border");
frame.setLayout(new BorderLayout());
frame.add(new JButton("north"), BorderLayout.NORTH);
frame.add(new JButton("south"), BorderLayout.SOUTH);
frame.add(new JButton("west"), BorderLayout.WEST);
frame.add(new JButton("east"), BorderLayout.EAST);
frame.add(new JButton("center"),
BorderLayout.CENTER);
frame.setVisible(true);
}
}
33
Complex layouts
• How would you create a complex window like this, using the layout
managers shown?
34
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
• example:
– how many panels?
– what layout in each?
35
Composite layout
example
import java.awt.*;
import javax.swing.*;
public class Telephone {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(250, 200));
frame.setTitle("Telephone");
frame.setLayout(new BorderLayout());
JPanel centerPanel = new JPanel(new GridLayout(4, 3));
for (int i = 1; i <= 9; i++) {
centerPanel.add(new JButton("" + i));
}
centerPanel.add(new JButton("*"));
centerPanel.add(new JButton("0"));
centerPanel.add(new JButton("#"));
frame.add(centerPanel, BorderLayout.CENTER);
JPanel southPanel = new JPanel(new FlowLayout());
southPanel.add(new JLabel("Number to dial: "));
southPanel.add(new JTextField(10));
frame.add(southPanel, BorderLayout.SOUTH);
frame.setVisible(true);
}
36
}