CSE 501N Fall ‘09 18: Java GUI (Swing)

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

description

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 - PowerPoint PPT Presentation

Transcript of CSE 501N Fall ‘09 18: Java GUI (Swing)

Page 1: CSE 501N Fall ‘09 18: Java GUI (Swing)

CSE 501NFall ‘0918: Java GUI (Swing)

10 November 2009

Nick Leidenfrost

Page 2: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 3: CSE 501N Fall ‘09 18: Java GUI (Swing)

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)

Page 4: CSE 501N Fall ‘09 18: Java GUI (Swing)

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)

Page 5: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 6: CSE 501N Fall ‘09 18: Java GUI (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

Page 7: CSE 501N Fall ‘09 18: Java GUI (Swing)

7

Java GUIjava.awt

Component

Container

Window

Frame

javax.swing

JComponent

JWindow

JFrame

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

Page 8: CSE 501N Fall ‘09 18: Java GUI (Swing)

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)

Page 9: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

}

Page 10: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

}

Page 11: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

}

Page 12: CSE 501N Fall ‘09 18: Java GUI (Swing)

12

Representing Choices in the GUI

Radio buttons JRadioButton

Check boxes JCheckBox

Combo boxes JComboBox

Page 13: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 14: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 15: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 16: CSE 501N Fall ‘09 18: Java GUI (Swing)

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;

Page 17: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 18: CSE 501N Fall ‘09 18: Java GUI (Swing)

18

Check Boxes

Construct by giving the name in the constructor:

Don't place into a button group

JCheckBox italicCheckBox = new JCheckBox("Italic");

Page 19: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 20: CSE 501N Fall ‘09 18: Java GUI (Swing)

20

Combo Boxes

Figure 4:An Open Combo Box

Page 21: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 22: CSE 501N Fall ‘09 18: Java GUI (Swing)

22

Combo Boxes

Get user selection with getSelectedItem (return type is Object)

Select an item programmatically with setSelectedItem

String selectedString =

(String) fontCombo.getSelectedItem();

Page 23: CSE 501N Fall ‘09 18: Java GUI (Swing)

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…

Page 24: CSE 501N Fall ‘09 18: Java GUI (Swing)

24

Borders

TitledBorder: a border with a title

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

Page 25: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 26: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 27: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 28: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 29: CSE 501N Fall ‘09 18: Java GUI (Swing)

30

Text Areas

Page 30: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 31: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 32: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 33: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 34: CSE 501N Fall ‘09 18: Java GUI (Swing)

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)

Page 35: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 36: CSE 501N Fall ‘09 18: Java GUI (Swing)

38

Border Layout

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

Page 37: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 38: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 39: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 40: CSE 501N Fall ‘09 18: Java GUI (Swing)

42

Grid Layout

Page 41: CSE 501N Fall ‘09 18: Java GUI (Swing)

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!

Page 42: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 43: CSE 501N Fall ‘09 18: Java GUI (Swing)

45

Example

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

alive?

Page 44: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 45: CSE 501N Fall ‘09 18: Java GUI (Swing)

47

Reading Text Input

Page 46: CSE 501N Fall ‘09 18: Java GUI (Swing)

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

Page 47: CSE 501N Fall ‘09 18: Java GUI (Swing)

49

Conclusion

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