CSE 501N Fall ‘09 18: Java GUI (Swing) 10 November 2009 Nick Leidenfrost

Preview:

Citation preview

CSE 501NFall ‘0918: Java GUI (Swing)

10 November 2009

Nick Leidenfrost

2

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

3

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)

4

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)

5

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

6

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

7

Java GUIjava.awt

Component

Container

Window

Frame

javax.swing

JComponent

JWindow

JFrame

What the ??? Why is there no Swing equivalent!?

8

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.

In the most pure sense of a “Container”, most often we will be using a JPanel A Container is-a Component As the name suggests, a container contains additional graphical objects

(components)

JWindow Represents an application window on your desktop A JWindow is-a JContainer

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

Is-A(G

enerally)

9

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

}

10

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);

}

11

JComponent

There are many types of JComponentFor example, a JButton is a JComponent

public void addButtonToPanel() {JPanel panel = new JPanel();JButton button = new JButton(“Click Me”);panel.add(button);

}

12

Representing Choices in the GUI

Radio buttons JRadioButton

Check boxes JCheckBox

Combo boxes JComboBox

13

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

14

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);

15

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);

16

Radio Buttons isSelected: called to find out if a button is

currently selected or not if

To set a default, call setSelected(true) on a radio button in group before making the enclosing frame visible

if (largeButton.isSelected()) size = LARGE_SIZE;

17

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

18

Check Boxes

Construct by giving the name in the constructor:

Don't place into a button group

JCheckBox italicCheckBox = new JCheckBox("Italic");

19

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

20

Combo Boxes

Figure 4:An Open Combo Box

21

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

22

Combo Boxes

Get user selection with getSelectedItem (return type is Object)

Select an item programmatically with setSelectedItem

String selectedString =

(String) fontCombo.getSelectedItem();

23

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…

24

Borders

TitledBorder: a border with a title

panel.setBorder(new TitledBorder(new EtchedBorder(), “Font Style”));

25

Menus A frame can contain a menu bar The menu bar contains menus A menu contains submenus and menu items

Menu Bar

File

Menu

Menu Items

New

Close

Open

Menu Items

Sub Menu (really just a Menu inside a Menu)

Open Recent

26

Menus Create Menu Bars with the JMenuBar class Create Menus with JMenu class Create Menu Items with JMenuItem class

JMenuBar

File

New

Close

Open

Open Recent

JMenuItem

JMenu

JMenuItem

JMenu

28

Text Areas Use a JTextArea to show multiple lines of text You can specify the number of rows and columns:

setText: to set the text of a text field or text area append: to add text to the end of a text area

final int ROWS = 10; final int COLUMNS = 30; JTextArea textArea = new JTextArea(ROWS, COLUMNS);

29

Text Areas

Use newline characters to separate lines:

To use for display purposes only: (do not let users edit the Text Area)

textArea.append(account.getBalance() + "\n");

textArea.setEditable(false); // program can call setText and append to change it

30

Text Areas

31

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);

32

Text Field

Input a single line of text Can set it to be editable or not Can obtain the text using the getText()

methodMy First GUI

Submit

34

What else?

Swing offers many more classes and options to tweak the look and feelExplore using APIs in Javadoc onlineGreat tutorialsAnything in the javax.swing package is fair

game

35

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

36

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)

37

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());

38

Border Layout

Border layout groups container into five areas: center, north, west, south and east

39

Border Layout

Default layout manager for a frame (technically, the frame's content pane)

When adding a component, specify the position like this:

Expands each component to fill the entire allotted area If that is not desirable, place each component inside a

panel

panel.add(component, BorderLayout.NORTH);

40

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

41

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); . . .

42

Grid Layout

43

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!

44

Grid Bag Layout

Fortunately, you can create acceptable-looking 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

45

Example

Expanding the simple GUI Next time: How do we make the GUI come

alive?

46

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);

47

Reading Text Input

48

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);

49

Conclusion

Questions? I’ll be in lab now until 6:45

Recommended