0% found this document useful (0 votes)
55 views

TCSS 143, Autumn 2004 Lecture Notes: Graphical User Interfaces Koffman/Wolfgang Appendix C, Pp. 747-786

This document provides an overview of creating graphical user interfaces (GUIs) in Java using Swing. It introduces JOptionPane as the simplest way to create dialog boxes. The document describes the Swing component hierarchy and common methods for components like JFrame, JButton, JLabel. It also covers containers, layout managers like BorderLayout and FlowLayout that control component positioning and sizing, and issues around component resizing. The goal is to teach how to construct basic GUIs in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

TCSS 143, Autumn 2004 Lecture Notes: Graphical User Interfaces Koffman/Wolfgang Appendix C, Pp. 747-786

This document provides an overview of creating graphical user interfaces (GUIs) in Java using Swing. It introduces JOptionPane as the simplest way to create dialog boxes. The document describes the Swing component hierarchy and common methods for components like JFrame, JButton, JLabel. It also covers containers, layout managers like BorderLayout and FlowLayout that control component positioning and sizing, and issues around component resizing. The goal is to teach how to construct basic GUIs in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 41

TCSS 143, Autumn 2004

Lecture Notes
Graphical User Interfaces
Koffman/Wolfgang Appendix
C,
pp. 747-786
1

Motivation

learn how to create a graphical user interface


(GUI) using Java and Swing
understand Java graphical component hierarchy
learn Java's event-driven model
banish the evil black box to the fiery depths
from which it came

Simplest GUI
programming:
JOptionPane

An option pane is a simple dialog box for graphical


input/output

advantages:

simple
flexible (in some ways)
looks better than the black box of doom

disadvantages:

created with static methods;


not very object-oriented
not very powerful (just simple dialog boxes)

Types of JOptionPanes

public static void showMessageDialog(


Component parent, Object message)
Displays a message on a dialog
with an OK button.

public static int showConfirmDialog(


Component parent, Object message)
Displays a message and list of
choices Yes, No, Cancel

public static String showInputDialog(


Component parent, Object message)
Displays a message and text
field for input, and returns the
value entered as a String.

JOptionPane examples 1

showMessageDialog analogous to System.out.println


for displaying a simple message

import javax.swing.*;
class MessageDialogExample {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null,
"How's the weather?");
JOptionPane.showMessageDialog(null,
"Second message");
}
}

JOptionPane examples 2

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.*;
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.");
}
}
}

JOptionPane examples 3

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.*;
class InputDialogExample {
public static void main(String[] args) {
String name = JOptionPane.showInputDialog(null,
"What's yer name, pardner?");
JOptionPane.showMessageDialog(null, "Yeehaw, " + name);
}
}

Onscreen GUI elements

windows: actual first-class citizens of desktop;


also called top-level containers
examples: frame, dialog box
components: GUI widgets
examples: button, text box, label
containers: logical grouping for components
example: panel

Java GUI: AWT and Swing

Suns initial idea: create a set of classes/methods


that can be used to write a multi-platform GUI
(Abstract Windowing Toolkit, or AWT)

Second edition (JDK v1.2): Swing

problem: not powerful enough; limited; a bit clunky to use

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!
9

Swing component
hierarchy
java.lang.Object

+--java.awt.Component
+--java.awt.Container
|
+--javax.swing.JComponent
|
+--javax.swing.JButton
|
+--javax.swing.JLabel
|
+--javax.swing.JMenuBar
|
+--javax.swing.JOptionPane
|
+--javax.swing.JPanel
|
+--javax.swing.JTextArea
|
+--javax.swing.JTextField
|
+--java.awt.Window
+--java.awt.Frame
+--javax.swing.JFrame

import java.awt.*;
import javax.swing.*;

10

Methods of all Swing


components

public int getWidth()


public int getHeight()
Allow access to the component's current width and
height in pixels.

public boolean isEnabled()


Returns whether the component is enabled (can be
interacted with).

public boolean isVisible()


Returns whether the component is visible (can be seen
on the screen).
11

More JComponent methods

public void setBackground(Color c)


Sets the background color of the component to be the given
color.

public void setFont(Font f)


Sets the font of the text on the given component to be the
given font.

public void setEnabled(boolean b)


Sets whether the component is enabled (can be interacted
with).

public void setVisible(boolean b)


Sets whether the component is visible (can be seen on the
screen). Set to true to show the component, or set to false
to hide the component.
12

JFrame
A frame is a graphical window that can
be used to hold other components

public JFrame()
or
public JFrame(String title)
Creates a frame with an optional title.

public void setTitle(String text)


Puts the given text in the frames 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?

public void pack()


Resizes the frame to fit the components inside it.
NOTE: Call setVisible(true) to make a frame appear on the screen after creating
it.
13

JButton, JLabel
The most common component
a button is a clickable onscreen
region that the user interacts with
to perform a single command
A text label is simply a string of text
displayed on screen in a graphical
program. Labels often give information or describe other components

public JButton(String text)


public JLabel(String text)
Creates a new button / label with the given string as its text.

public String getText()


Returns the text showing on the button / label.

public void setText(String text)


Sets button / label's text to be the given string.

14

JTextField, JTextArea
A text field is like a label, except that the text
in it can be edited and modified by the user.
Text fields are commonly used for user input,
where the user types information in the field
and the program reads it
A text area is a multi-line text field

public JTextField(int columns)


public JTextArea(int lines, int columns)
Creates a new text field that is the given number of columns
(letters) wide.

public String getText()


Returns the text currently in the field.

public void setText(String text)


Sets field's text to be the given string.

15

JCheckBox, JRadioButton
A check box is a toggleable button with two states:
checked and unchecked
A radio button is a button that can be selected; usually part of a
group of mutually-exclusive radio buttons (1 selectable at a time)

public JCheckBox / JRadioButton(String text)


public JCheckBox(String text, boolean isChecked)
Creates checked/unchecked check box with given text.

public boolean isSelected()


Returns true if check box is checked.

public void setSelected(boolean selected)


Sets box to be checked/unchecked.

16

ButtonGroup
A logical group of radio buttons that ensures
that only one is selected at a time

public ButtonGroup()
public void add(JRadioButton button)

The ButtonGroup is not a graphical component, just a


logical group; the RadioButtons themselves are added
to the container, not the ButtonGroup

17

Problem: positioning,
resizing
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?

Absolute positioning (C++, C#, others):


Specify exact pixel coordinates for every
component

Layout managers (Java):


Have special objects that decide where to
position each component based on some
criteria

What are benefits or drawbacks to each approach?


18

Containers with layout

The idea: Place many components into a container(s),


then add the container(s) to the JFrame

19

Container
A container is an object that holds components; it also
governs their positions, sizes, and resize behavior

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.
20

JPanel
A panel is our container of choice; it inherits the
methods from the previous slide and defines
these additional methods (among others):

public JPanel()
Constructs a panel with a default flow layout.

public JPanel(LayoutManager mgr)


Constructs a panel that uses the given
layout manager.

21

Preferred size of
components
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

Buttons at preferred size:

Not preferred size:

22

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

Container panel = new JPanel(new BorderLayout());


panel.add(new JButton("Button 1 (NORTH)", BorderLayout.NORTH);

23

FlowLayout
public FlowLayout()

treats container as a left-to-right, top-to-bottom "page"


or "paragraph"
components are given their preferred size both
horizontally and vertically
components are positioned in order added
if too long, components wrap around to next line

Container panel = new JPanel(new FlowLayout());


panel.add(new JButton("Button 1"));

24

GridLayout
public GridLayout(int rows, int columns)

treats container as a grid of equally-sized rows


and columns
components are given equal horizontal /
vertical size, disregarding preferred size
can specify 0 rows or columns to indicate
expansion in that direction as needed

25

BoxLayout
Box.createHorizontalBox()
Box.createVerticalBox()

aligns components in container in a single


row or column
components use preferred sizes and align
based on their preferred alignment
preferred way to construct a container with box
layout:
Box.createHorizontalBox(); or
Box.createVerticalBox();
26

Other layouts

CardLayout
layers of "cards" stacked
on top of each other;
one visible at a time

GridBagLayout
very complicated;
my recommendation:
never ever use it

custom / null layout


allows you to define absolute positions using setX/Y
and setWidth/Height
27

Problem with layout


managers
How would you create a complex window like this,
using the layout managers shown?

28

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?

29

For next time...

What is missing?

Why don't the buttons do anything when we


click them?
How can we fix this problem?

Next lecture: events

(making the GUI responsive to user


interaction)
allows our own GUIs to be interactive like
JOptionPane
30

Event-driven Programming

programs 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)
31

Java Event Hierarchy


java.lang.Object
+--java.util.EventObject
+--java.awt.AWTEvent
+--java.awt.event.ActionEvent
+--java.awt.event.TextEvent
+--java.awt.event.ComponentEvent
+--java.awt.event.FocusEvent
+--java.awt.event.WindowEvent
+--java.awt.event.InputEvent
+--java.awt.event.KeyEvent
+--java.awt.event.MouseEvent

import java.awt.event.*;
32

Action events
(
ActionEvent)
most common / simple event type in Swing
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.

33

Listening for events

attach listener to component


listeners appropriate method will be called
when event occurs (e.g. when the button is
clicked)
for Action events, use ActionListener

34

Writing an ActionListener
// part of Java; you dont write this
public interface ActionListener {
void actionPerformed(ActionEvent event);
}
// Prints a message when the button is clicked.
public class MyActionListener
implements ActionListener {
public void actionPerformed(ActionEvent event){
System.out.println("Event occurred!");
}
}
35

Attaching an
ActionListener
JButton button = new JButton("button

1");
ActionListener listener = new MyActionListener();
button.addActionListener(listener);

now button will print "Event occurred!" when


clicked
addActionListener method exists in many Swing
components

36

ActionEvent objects

public Object getSource()


Returns object that caused this event to
occur.

public String getActionCommand()


Returns a string that represents this event.
(for example, text on button that was
clicked)

Question: Where to put the listener class? 37

Inner class listener


public class Outer {
private class Inner implements ActionListener {
public void actionPerformed(
ActionEvent event) {
...
}
}
public Outer() {
JButton myButton = new JButton();
myButton.addActionListener(new Inner());
}
}

38

Anonymous inner listener


public class Outer {
public Outer() {
JButton myButton = new JButton();
myButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {

...
}
}
);
}
}

39

ActionListener in JFrame
public class Outer extends JFrame
implements ActionListener {
public Outer() {
JButton myButton = new JButton();
myButton.addActionListener(this);
}
public void actionPerformed(ActionEvent event) {
...
}
}

40

References

The Java Tutorial: Visual Index to the Swing


Components.
http://java.sun.com/docs/books/tutorial/
uiswing/components/components.html

The Java Tutorial: Laying Out Components Within a


Container.
http://java.sun.com/docs/books/tutorial/uiswing/
layout/index.html

The Java Tutorial: How to Write Action Listeners.


http://java.sun.com/docs/books/tutorial/
uiswing/events/actionlistener.html
41

You might also like