layout manager

Download Report

Transcript layout manager

CSE 501N
Fall ‘09
18: Java GUI (Swing)
10 November 2009
Nick Leidenfrost
Lecture Outline



Lab 7 questions?
Application Programming Interfaces (APIs)
Java Graphical User Interface basic concepts

Basic classes
 Layout management

Java Components / Controls
 Labels
 Buttons
 Text boxes
 Text areas
 Others
2
Application Programming Interface


Most often referred to by its acronym, API
The set of public fields and methods a class
makes available to a programmer
 A.k.a.


a class’s published interface
The API encompasses any interaction that can
be made with a module in a program
Simple but important concept

(I will probably* ask you to explain this on the final
exam.)
 (*and by probably, I mean definitely)
3
Graphical User Interface


A.k.a. GUI (goo – ee)
Most programs provide a graphical interface for the user
to interact with


(duh.)
The benefits of using a GUI are numerous




More logical presentation of data
More intuitive interaction with the user
Without GUIs, we would have no way of displaying silly clip-art
(I can’t stand to see you cry, little orange man)
4
Java GUI


The Java Library provides two ways of creating
Graphical User Interfaces (GUIs)
Abstract Windowing Toolkit (AWT)
 Java
asks the underlying operating system (OS) to
supply the implementation for some graphical
elements: buttons, text fields, etc.
 Contained in the package java.awt

Swing
 Graphical
elements are implemented internally, with
little dependency on OS support
 Provides higher levels of functionality
 Looks more standardized across platforms
 Contained in the package javax.swing
5
Java GUI



The history of AWT and Swing can provide some
insight when working with the libraries
AWT came first
Many classes which “support” GUIs, but do not
themselves have graphical representation are
contained in AWT
 These
classes are used by Swing classes and are not
duplicated in Swing

Many Swing classes with graphical
representation may seem like duplicates, or
mirrors of their respective AWT classes
6
Java GUI
java.awt
javax.swing
Component
JComponent
Container
Window
JWindow
Frame
JFrame
What the ??? Why is there no Swing
equivalent!?
7
Java GUI


JComponent

Extends Component

A basic graphical object, e.g., buttons, labels, images, etc.
Container


Something that you can place other graphical objects on
Is an abstract class.


JWindow



A Container is-a Component
As the name suggests, a container contains additional graphical objects
(components)
Represents an application window on your desktop
A JWindow is-a JContainer
Is-A
(Generally)


In the most pure sense of a “Container”, most often we will be using a JPanel
JFrame



A window with a title bar, and buttons to close, minimize and maximize
A JFrame is-a JWindow
Can put any content inside it
8
JFrame

To create a GUI which creates a window,
simply extend the JFrame class
public class MyFrame extends JFrame {
public MyFrame() {
super(“My First Frame”);
}
// Other methods
}
9
JContainer

The most common container is the JPanel
 Think
of it as a flat tray on which you can lay out other
components (or containers)
 You can add components by using the add method
 You may also remove components from the panel
public void addToPanel (Component c) {
JPanel panel = new JPanel();
panel.add(c);
}
10
JComponent

There are many types of JComponent
 For
example, a JButton is a JComponent
public void addButtonToPanel() {
JPanel panel = new JPanel();
JButton button = new JButton(“Click Me”);
panel.add(button);
}
11
Representing Choices in the GUI

Radio buttons


Check boxes


JRadioButton
JCheckBox
Combo boxes

JComboBox
12
Radio Buttons

For a small set of mutually exclusive choices,
use radio buttons or a combo box

In a radio button set, only one button can be
selected at a time

When a button is selected, previously selected
button in set is automatically turned off
13
Radio Buttons

In previous figure, font sizes are mutually
exclusive:
JRadioButton smallButton = new JRadioButton("Small");
JRadioButton mediumButton = new JRadioButton("Medium");
JRadioButton largeButton = new JRadioButton("Large");
// Add radio buttons into a ButtonGroup so that
// only one button in group is on at any time
ButtonGroup group = new ButtonGroup();
group.add(smallButton);
group.add(mediumButton);
group.add(largeButton);
14
Radio Buttons

Button group does not add buttons to the
container for you


It only creates a mutually exclusive relationship
between buttons
You still have to add buttons to the container
ButtonGroup group = new ButtonGroup();
group.add(smallButton);
group.add(mediumButton);
group.add(largeButton);
container.add(smallButton);
container.add(mediumButton);
container.add(largeButton);
15
Radio Buttons

isSelected: called to find out if a button is
currently selected or not if
if (largeButton.isSelected()) size = LARGE_SIZE;

To set a default, call setSelected(true) on
a radio button in group before making the
enclosing frame visible
16
Check Boxes


Two states: checked and unchecked
Use one checkbox for a binary choice



(or a boolean choice: yes / no, on / off, true / false)
Use a group of check boxes when one
selection does not exclude another
Example: "bold" and "italic" in previous figure
17
Check Boxes

Construct by giving the name in the
constructor:
JCheckBox italicCheckBox = new JCheckBox("Italic");

Don't place into a button group
18
Combo Boxes

For a large set of choices, use a combo box
 Uses less space than radio buttons

"Combo": combination of a list and a text field
 The text field displays the name of the
current selection
19
Combo Boxes
Figure 4:
An Open Combo Box
20
Combo Boxes

If combo box is editable, user can type own
selection


Specified with setEditable method
Add strings with addItem method:
JComboBox fontCombo = new JComboBox();
fontCombo.addItem("Serif");
fontCombo.addItem("Sans Serif");
. . .
21
Combo Boxes

Get user selection with getSelectedItem
(return type is Object)
String selectedString =
(String) fontCombo.getSelectedItem();

Select an item programmatically with
setSelectedItem
22
Borders



Place a border around a panel to group
its contents visually
EtchedBorder: three-dimensional
etched effect
Can add a border to any component, but
most commonly to panels:
Jpanel panel = new JPanel ();
panel.setBOrder(new EtchedBorder ());
Continued…
23
Borders

TitledBorder: a border with a title
panel.setBorder(new TitledBorder(new EtchedBorder(), “Font Style”));
24
Menus

A frame can contain a menu bar
The menu bar contains menus

A menu contains submenus and menu items

Menu Bar
Menu
File
New
Menu Items
Close
Open
Sub Menu (really just a Menu inside a Menu)
Open Recent
Menu Items
25
Menus



Create Menu Bars with the JMenuBar class
Create Menus with JMenu class
Create Menu Items with JMenuItem class
JMenuBar
JMenu
File
New
JMenuItem
Close
Open
JMenu
Open Recent
JMenuItem
26
Text Areas

Use a JTextArea to show multiple lines of text

You can specify the number of rows and
columns:
final int ROWS = 10;
final int COLUMNS = 30;
JTextArea textArea = new JTextArea(ROWS, COLUMNS);


setText: to set the text of a text field or text
area
append: to add text to the end of a text area
28
Text Areas

Use newline characters to separate lines:
textArea.append(account.getBalance() + "\n");

To use for display purposes only:

(do not let users edit the Text Area)
textArea.setEditable(false);
// program can call setText and append to change it
29
Text Areas
30
Scrolling with JScrollPane
To add scroll bars to a text area, or any
component:
JTextArea textArea = new JTextArea(ROWS, COLUMNS);
JScrollPane scrollPane = new JScrollPane(textArea);
31
Text Field
Input a single line of text
 Can set it to be editable or not
 Can obtain the text using the getText()
method

My First GUI
Submit
32
What else?

Swing offers many more classes and
options to tweak the look and feel
 Explore
using APIs in Javadoc online
 Great tutorials
 Anything in the javax.swing package is fair
game
34
Layout Management

By default, we have had very limited
control over how components are
positioned

When we used a panel, it arranged the
components from the left to the right
35
Layout Management

Each Container has a layout manager that
directs the arrangement of its components

Three useful layout managers:




BorderLayout
GridLayout
GridBagLayout
Layout managers are part of the java.awt
package

(although they affect display, they themselves have
no graphical representation)
36
Layout Management

By default, JPanel places components from left to
right and starts a new row when needed

Panel layout carried out by FlowLayout layout
manager

Can set other layout managers
panel.setLayout(new BorderLayout());
37
Border Layout

Border layout groups
container into five
areas: center, north,
west, south and east
38
Border Layout


Default layout manager for a frame (technically,
the frame's content pane)
When adding a component, specify the position
like this:
panel.add(component, BorderLayout.NORTH);


Expands each component to fill the entire allotted
area
If that is not desirable, place each component
inside a panel
39
Grid Layout



Arranges components in a grid with a
fixed number of rows and columns
Resizes each component so that they all
have same size
Expands each component to fill the entire
allotted area
40
Grid Layout

Add the components, row by row, left to
right:
JPanel numberPanel = new JPanel();
numberPanel.setLayout(new GridLayout(4, 3));
numberPanel.add(button1);
numberPanel.add(button2);
numberPanel.add(button3);
numberPanel.add(button4);
. . .
41
Grid Layout
42
Grid Bag Layout

Tabular arrangement of
components

Columns can have
different sizes
 Components can span
multiple columns

Quite complex to use


Will not cover or assign
in labs
If you are a masochist,
this is the layout
manager for you!
43
Grid Bag Layout

Fortunately, you can create acceptablelooking layouts by nesting panels

Give each panel an appropriate layout
manager
 Panels don’t have visible borders
 Use as many panels as needed to organize
components
44
Example
Expanding the simple GUI
 Next time: How do we make the GUI come
alive?

45
Prompting a User for Input

A graphical application can obtain input by displaying a
JOptionPane

The showInputDialog method displays a prompt
and waits for user input

The showInputDialog method returns the string
that the user typed
String input = JOptionPane.showInputDialog("Enter x");
double x = Double.parseDouble(input);
46
Reading Text Input
47
Colors

Standard colors Color.BLUE, Color.RED,
Color.PINK etc.

Specify red, green, blue between 0.0F and 1.0F
Color magenta = new Color(1.0F, 0.0F,
1.0F); // F = float

Specify RGB values between 0 and 255 int
Color c = new Color(255, 0, 0);
48
Conclusion
Questions?
 I’ll be in lab now until 6:45

49