145
Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

  • View
    244

  • Download
    5

Embed Size (px)

Citation preview

Page 1: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java Programming

Transparency No. 1

Lecture 9 Java GUI

Cheng-Chia Chen

Page 2: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 2

Contents

1. java GUI evolution

2. Swing Components and Containing Hierarchy

3. Layout Management

4. Java Event Model and Event Handling

5. javaBeans

Reference: The Java Tutorial on the trail: Creating a GUI with JFC/Swing

Page 3: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 3

Evolution of Java GUI

Java 1.0 AWT built in 30 days, and it shows Java 1.1 AWT significantly improved, but GUI not

finished yet Java 2 Swing: very different, vastly improved This lecture cover Swing only.

Page 4: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 4

Swing/JFC is very powerful

Start with the simple approach so you can create basic applications

Most of the time this will satisfy your needs If you want to modify the standard elements, you can, b

ut... You’ll have to work harder and learn more A number of big, thick books are available

Page 5: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 5

Swing/JFC

Very easy to add keyboard accelerators, tooltips, graphics

Pluggable look and feel Provides ways to change just about everything, but you

must work to understand how

Page 6: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 6

Swing Components and the containment hierarchy

Borders Buttons Checkboxes ComboBoxes Image Icons Labels Layered Panes and Internal

Frames (MDI) Lists and List Boxes

Menus Popup Menus Radio Buttons Progress Bars Scrolling Support Scrollbars Splitter Control Tabbed Panes

Page 7: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 7

Swing features and Conecpts

Components and the containment hierarchy Swing Components and the Containment Hierarchy Layout Management Event Handling Painting Threads and Swing More Swing Features and Concepts The Anatomy of a Swing-Based Program

Page 8: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 8

Swing Components and the Containment Hierarchy

An example:

Four components in this GUI: a frame, or main window (JFrame) --- top-level container a panel, sometimes called a pane (JPanel) --- intermediate container a button (JButton) --- atomic components a label (JLabel) --- atomic components

Page 9: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 9

the containment hierarchy for the gui:

Page 10: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 10

The code that adds the button and label to the panel, and the panel to the content pane:

frame = new JFrame(...);

button = new JButton(...);

label = new JLabel(...);

pane = new JPanel();

pane.add(button);

pane.add(label);

frame.getContentPane().add(pane, BorderLayout.CENTER);

Page 11: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 11

Classification of swing components

Top-Level Containers The components at the top of any Swing containment hierarchy.

General-Purpose Containers Intermediate containers that can be used under many different circumstances.

Special-Purpose Containers Intermediate containers that play specific roles in the UI.

Basic Controls Atomic components that exist primarily to get input from the user; they generally also show simple state.

Uneditable Information Displays Atomic components that exist solely to give the user information.

Editable Displays of Formatted Information Atomic components that display highly formatted information that (if you choose) ca

n be edited by the user.

Page 12: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 12

top-level containers

Frame ( and JFrame)

Dialog ( and JDialog)

Applet (and JApplet)

Page 13: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 13

General-Purpose Containers

Panel ( and JPanel)

JToolBar

JScrollPane

JTabbedPane

JSplitPane

Page 14: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 14

Special-Purpose Containers

JLayeredPaneJInternalFrames

Root Pane

Page 15: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 15

Basic Controls

JCheckBoxJRadioButtonJButton

JMenuJMenuItem

List ( and JList)

Page 16: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 16

Basic Controls

Choice ( and JComboBox) JTextField

JSlider

Page 17: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 17

Uneditable Information Displays

Label ( and JLabel)

JProgressBar

JToolTip

Page 18: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 18

Editable Displays of Formatted Information

JTree JText JTable

FileDialog ( and JFileChooser)JColorChooser

Page 19: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 19

Structure of the java.awt (AWT) package.

Component{abstract}

ComponentPeer

ImageObserver

LayoutManager

Font

TextComponent

CheckboxCanvasButton Choice

Color

Label

TextFieldTextArea

List

Container{abstract}

Scrollbar

-parent

-peer

-layoutMgr

Page 20: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 20

Layout Management

the GUIs of five programs, each of which displays five buttons.

Page 21: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 21

Common layout tasks

Identical Buttons, almost identical codes. why do they look so different? use different layout managers to control the size and position of the buttons.

the common layout tasks: Setting the layout manager : JPanel pane = new JPanel(); pane.setLayout(new BorderLayout()); Providing hints about a component : privide size Hints : setMinimumSize(Dimension), setPreferredSize(..), setMaximumSi

ze(..) provide alignmentHints: setAllignmentX(float), setAlignmentY(float) Putting space between components : the layout manager : can specify hgap and vgap. putting invisible component: empty border : best for components that have no default border, eg: JPanel, Jlabel

Page 22: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 22

Event Handling

Every time the user types a character (KeyEvent) or pushes a mouse button( MouseEvent), an event occurs.

Any object can be notified of the event. implement the appropriate interface and be registered as an event listener on the appropriate event source.

Swing components can generate many kinds of events.

Page 23: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 23

Example GUI Events

Act that results in the event Listener type User clicks a button,

presses Return while typing in a ActionListener

text field, or chooses a menu item

User closes a frame (main window) WindowListener User presses a mouse button

while the cursor is over a component MouseListener User moves the mouse over a component MouseMotionListener Component becomes visible ComponentListener Component gets the keyboard focus FocusListener Table or list selection changes ListSelectionListener

Page 24: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 24

Java Event Model

delegation ( or forwarding ) model

l:EventListner

b:EventSource

system:

l = new EventListener(…)

b=new EventSource(…)

addXXXListener(l) Event e1 occurs

doXXXAction(e1)

Event e2 occurs

doXXXAction(e2)

….

Page 25: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 25

How to Implement an Event Handler

Implement and instantiate an event Listener : public class MyClass implements XXXListener { …} XXXListener l = (XXXListener) new MyClass(…);

Register the eventListener as an listener on event source: aEventSource.addXXXListener( l ) ;

From now on, every time an event e occurs, the event source object will call the appropriate doXXXAction(e) from l.

Threads and Event Handling : Event-handling code executes in a single thread, the event-dispatching t

hread. => Event handlers should execute very quickly, Otherwise, the program's

perceived performance will be poor. If needing lengthy operation, starting up another thread

Page 26: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 26

How Painting Works

1. background

2. custom painting

3. border

4. children

Page 27: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 27

More Swing Features and Concepts Features that JComponent provides

the ability to have borders, tool tips, and a configurable look and feel.

Icons Many Swing components -- notably buttons and labels -- can display images. You s

pecify these images as Icon objects. Actions

provide support for sharing data and state between two or more components that can generate action events.

Pluggable Look & Feel support A single program can have any one of several looks and feels. can let the user determine the look and feel, or can specify the look and feel programatically.

Support for assistive technologies Separate data and state models

Page 28: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 28

Using Swing Components

The JComponent Class Using Top-Level Containers Using Intermediate Swing Containers Using Atomic Components

Page 29: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 29

The JComponent Class

JComponent Container Component Tool tips:

setToolTipText(String) Borders

The setBorder method allows you to specify the border that a component displays around its edges.

Keyboard-generated actions Using the registerKeyboardAction method, you can enable the user to

use the keyboard, instead of the mouse, to operate the GUI. Application-wide pluggable look and feel

UIManager.setLookAndFeel(…) Properties

can associate one or more properties (name/object pairs) with any JComponent.

putClientProperty(…), getClientProperty(…)

Page 30: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 30

Support for layout get/set minimum/preferred/maximum Size(..). get/set alignmentX/Y(…)

Support for accessibility Double buffering Methods to increase efficiency

getX(), getY(), getWidth(), getHeight(),…

Page 31: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 31

The JComponent API

Customizing Component Appearance : get/set for properties: border, forground, background, font, opaque eg: setBorder(Border) / Border getBorder(), …

Setting Component State void setToolTipText(String) void setEnabled(boolean b) , boolean isEnabled() void setLocale(Locale l) , Locale getLocale() void setCursor(Cursor), Cursor getCursor() // mouse curser Icon void setVisible(boolean) , boolean isVisible()

Handling Events : add/remove (component, mouse, mouseMotion, key, container, focus) Listenser get/set nextFocusComponent property requestFocus(), hasFocus() boolean contains(int x, int y), contains(Point) Component getComponentAt(int, int)

Page 32: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 32

Painting Components void repaint() , repaint(int, int, int, int), repaint(Rectangle) void revalidate() : ReLay out the component and its affected containers. void paintComponent(Graphics)

Dealing with the Containment Hierarchy Component add(Component [, int index | Object constraint ] ) void remove(int) , void remove(Component comp) , void removeAll() JRootPane getRootPane() Container getParent() int getComponentCount() Component getComponent(int) Component[] getComponents()

Page 33: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 33

Laying Out Components get/set LayoutManager property: layout get/set Dimension properties: minimumSize, preferredSize, maximumSize get/set float property: allignmentX, allignmentY

Getting Size and Position Information int getWidth(), getHeight(), getX(), getY() Dimension getSize(), Dimension getSize(Dimension) Rectangle getBounds() , Rectangle getBounds(Rectangle) Point getLocation() , getLocation(Point), getLocationOnScreen(); Insets getInsets()

Specifying Absolute Size and Position setLocation(int,int) setLocation(Point), setSize(int,int), setSize(Dimensi

on), setBounds(int x,y,w,h), setBounds(Rectangle)

Page 34: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 34

Using Top-Level Containers

three generally useful top-level container classes: JFrame, JDialog, and JApplet.

Each has a content pane that contains the visible components in the GUI.

Can optionally add a menu bar to a top-level container. positioned within the top-level container, but outside the content pane.

Page 35: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 35

Adding Components to the Content Pane : frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);

Adding a Menu Bar : frame.setJMenuBar(cyanMenuBar);

The Root Pane :

Page 36: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 36

How to Make Frames (Main Windows)

code creates and sets up the frame

Page 37: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 37

the code

public static void main(String s[]) { JFrame frame = new JFrame("FrameDemo");

frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} });

//...create a blank label, set its preferred size...

frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);

frame.pack(); frame.setVisible(true); }

Page 38: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 38

JFrame APIs

Constructors: JFrame(), JFrame(String) void setDefaultCloseOperation(int), int getDefaultCloseOperatio

n() Possible choices: DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE (the de

fault) , DISPOSE_ON_CLOSE

void setContentPane(Container) , Container getContentPane() void setJMenuBar(JMenuBar) , JMenuBar getJMenuBar() …

Page 39: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 39

Using Intermediate Swing Containers

Panel The most flexible, frequently used intermediate container.

Scroll Pane Provides scroll bars around a large or growable component.

Split Pane Displays two components in a fixed amount of space, letting the user

adjust the amount of space devoted to each component.

Tabbed Pane Contains multiple components but shows only one at a time. The user ca

n easily switch between components.

Tool Bar Holds a group of components (usually buttons) in a row or column,

optionally allowing the user to drag the tool bar into different locations.

Page 40: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 40

special intermediate containers

Internal Frame Looks like a frame and has much the same API, but must appear within

another window.

Layered Pane Provides a third dimension, depth, for positioning components. You

specify the position and size of each component. One type of layered pane, a desktop pane, is designed primarily to contain and manage internal frames.

Root Pane : Provides behind-the-scenes support to top-level containers.

Page 41: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 41

How to Use Panels

Page 42: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 42

Setting the Layout Manager : JPanel aPanel = new JPanel(); aPanel.setLayout(new BorderLayout());

Adding Components aFlowPanel.add(aComponent); aFlowPanel.add(anotherComponent); aBorderPanel.add(aComponent, BorderLayout.CENTER); aBorderPanel.add(anotherComponent, BorderLayout.SOUTH);

Page 43: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 43

The JPanel API

Constructors: JPanel() , JPanel(LayoutManager) void add(Component [, Object ] [, int ]), void add(String, Component) int getComponentCount() Component getComponent(int) Component[] getComponents() Component getComponentAt( [int, int | Point] ) void remove(Component), void remove(int) , void removeAll() void setLayout(LayoutManager), LayoutManager getLayout()

Page 44: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 44

How to Use Scroll Panes

textArea = new JTextArea(5, 30);JScrollPane scrollPane = new JScrollPane(textArea); ...contentPane.setPreferredSize(new Dimension(400, 100)); ...contentPane.add(scrollPane, BorderLayout.CENTER);

Page 45: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 45

How to use Split Pane

Page 46: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 46

the code

//Create a split pane with the two scroll panes in it.

splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,

listScrollPane, pictureScrollPane);

splitPane.setOneTouchExpandable(true);

splitPane.setDividerLocation(150);

//Provide minimum sizes for the two components in the split pane

Dimension minimumSize = new Dimension(100, 50);

listScrollPane.setMinimumSize(minimumSize);

pictureScrollPane.setMinimumSize(minimumSize);

Page 47: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 47

How to Use Tool Bars

Page 48: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 48

public ToolBarDemo() { ...

JToolBar toolBar = new JToolBar();

addButtons(toolBar);

...

JPanel contentPane = new JPanel();

contentPane.setLayout(new BorderLayout());

...

contentPane.add(toolBar, BorderLayout.NORTH);

contentPane.add(scrollPane, BorderLayout.CENTER);

...

}

Page 49: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 49

protected void addButtons(JToolBar toolBar) { JButton button = null; //first button button = new JButton(new ImageIcon("images/left.gif")); ... toolBar.add(button); //second button button = new JButton(new ImageIcon("images/middle.gif")); ... toolBar.add(button); //third button button = new JButton(new ImageIcon("images/right.gif")); ... toolBar.add(button); } Other methods:

isFloatable(), setFloatable(boolean) addSeparator()

Page 50: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 50

Using Atomic Components

The following atomic components exist primarily to get input from the user: Button, Check Box, Radio Button

Provides easy-to-use, easy-to-customize button implementations.

Combo Box Provides both uneditable and editable combo boxes -- buttons that bring up menus

of choices.

List Displays a group of items that the user can choose.

Menu Includes menu bar, menu, and menu item implementations, including specialized me

nu items such as check box menu items.

Slider Lets the user choose one of a continuous range of values.

Text Field Lets the user enter a single line of text data.

Page 51: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 51

Some atomic components exist only to give information: Label : Presents some text, an icon, or both. Progress Bar : Displays progress toward a goal. Tool Tip : Brings up a small window that describes another component.

The rest of the atomic components provide formatted information and a way of editing it:

Color Chooser : A UI for choosing colors; can be used inside or outside a dialog.

File Chooser :A UI for choosing files and directories. Table: An extremely flexible component that displays data in a grid

format. Text Support : A framework including everything from simple text

components, such as text fields, to a full-featured, extensible kit for building text editors.

Tree : A component that displays hierarchical data.

Page 52: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 52

How to Use Buttons, Check Boxes, and Radio Buttons

ImageIcon leftButtonIcon = new ImageIcon("images/right.gif")b1 = new JButton("Disable middle button", leftButtonIcon);b1.setVerticalTextPosition(AbstractButton.CENTER);

position of the text relative to the icon

b1.setHorizontalTextPosition(AbstractButton.LEFT);b1.setMnemonic(KeyEvent.VK_D);b1.setActionCommand("disable");b1.addActionListener(this); b1.setToolTipText(“… ");

Page 53: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 53

// can use setText(“<html> …<.html>”) for multiFonts text b1 = new JButton("<html><font size=-1> <b><u>D</u>isable</b

>“ + " middle button</font>", leftButtonIcon);

Page 54: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 54

How to Use Check Boxes

Page 55: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 55

the code

//In initialization code:

chinButton = new JCheckBox("Chin");

chinButton.setMnemonic(KeyEvent.VK_C);

chinButton.setSelected(true);

glassesButton = new JCheckBox("Glasses");

glassesButton.setMnemonic(KeyEvent.VK_G);

glassesButton.setSelected(true); …

// Register a listener for the check boxes.

CheckBoxListener myListener = new CheckBoxListener();

chinButton.addItemListener(myListener); …

teethButton.addItemListener(myListener);

Page 56: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 56

How to use RadioButtons

Radio buttons are groups of buttons in which, by convention, only one button at a time can be selected.

Swing release supports radio buttons with the JRadioButton and ButtonGroup classes.

Page 57: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 57

//In initialization code:

// Create the radio buttons.

JRadioButton birdButton = new JRadioButton(birdString);

birdButton.setMnemonic(KeyEvent.VK_B);

birdButton.setActionCommand(birdString);

birdButton.setSelected(true); …

// Group the radio buttons.

ButtonGroup group = new ButtonGroup();

group.add(birdButton); group.add(catButton);

group.add(dogButton); group.add(rabbitButton);

group.add(pigButton);

Page 58: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 58

// Register a listener for the radio buttons. RadioListener myListener = new RadioListener(); birdButton.addActionListener(myListener); catButton.addActionListener(myListener); dogButton.addActionListener(myListener); rabbitButton.addActionListener(myListener); pigButton.addActionListener(myListener); ... class RadioListener implements ActionListener ... { public void actionPerformed(ActionEvent e) { picture.setIcon(new ImageIcon("images/" + e.getActionCommand() + ".gif")); } }

Page 59: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 59

The event listener

class CheckBoxListener implements ItemListener { public void itemStateChanged(ItemEvent e) { ... Object source = e.getItemSelectable(); if (source == chinButton) { //...make a note of it... } else if (source == glassesButton) { //...make a note of it... } else if (source == hairButton) { //...make a note of it... } else if (source == teethButton) { //...make a note of it... } if (e.getStateChange() == ItemEvent.DESELECTED) //...make a note of it... picture.setIcon(/* new icon */); ... } }

Page 60: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 60

ColorChooser

Page 61: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 61

final JLabel banner = new JLabel("Welcome to the Tutorial Zone!",

JLabel.CENTER);

banner.setForeground(Color.yellow); ...

final JColorChooser tcc = new ColorChooser ( banner.getForeground()); // initial selected color ...

getContentPane().add(tcc, BorderLayout.CENTER); A color chooser uses an instance of ColorSelectionModel to co

ntain and manage the current selection, which fires a change event whenever the user changes the color in the color chooser.

Page 62: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 62

The example program registers a change listener with the color selection model so that it can update the banner at the top of the window. The following code registers and implements the change listener:

tcc.getSelectionModel().addChangeListener(

new ChangeListener() {

public void stateChanged(ChangeEvent e) {

Color newColor = tcc.getColor();

banner.setForeground(newColor);

} } );

Page 63: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 63

File Chooser

Page 64: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 64

//Create a file chooser final JFileChooser fc = new JFileChooser(); ...// Event Handler for the OpenFile buttonpublic void actionPerformed(ActionEvent e) { // container int returnVal = fc.showOpenDialog(FileChooserDemo.this); //= fc.showDialog(FileChooserDemo.this, “OK”) // other: fc.ShowSaveDialog(…) if (returnVal == JFileChooser.APPROVE_OPTION) { // other possibilities: CANCEL_OPTION, ERROR_OPTION File file = fc.getSelectedFile(); //this is where a real application would open the file. log.append("Opening: " + file.getName() + "." + newline); } else { log.append("Open command cancelled by user." + newline); } }

Page 65: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 65

Label

Page 66: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 66

ImageIcon icon = new ImageIcon("images/middle.gif"); . . .

// 2nd arg sets the position of contents relative to label label1 = new JLabel("Image and Text", icon, JLabel.CENTER); //Set the position of the text, relative to the icon: label1.setVerticalTextPosition(JLabel.BOTTOM); label1.setHorizontalTextPosition(JLabel.CENTER);

label2 = new JLabel("Text-Only Label");

label3 = new JLabel(icon);

//Add labels to the JPanel. add(label1); add(label2); add(label3);

Page 67: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 67

Using HTML on a Label

The action listener for the button executes this single line of code: theLabel.setText(htmlTextArea.getText());

Page 68: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 68

Combo Boxes

very different forms: uneditable and editable. Uneditable Combo Box: Editable Como Box

Page 69: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 69

String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" }; // Create the combo box, select item at index 4. // Indices start at 0, so 4 specifies the pig. JComboBox petList = new JComboBox(petStrings); petList.setSelectedIndex(4); ...petList.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox cb = (JComboBox)e.getSource(); String petName = (String)cb.getSelectedItem(); picture.setIcon(new ImageIcon("images/" + petName + ".gif")); } });

Page 70: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 70

String[] patternExamples = { "dd MMMMM yyyy", "dd.MM.yy", "MM/dd/yy", "yyyy.MM.dd G 'at' hh:mm:ss z",

"EEE, MMM d, ''yy", "h:mm a", "H:mm:ss:SSS", "K:mm a,z", "yyyy.MMMMM.dd GGG hh:mm aaa"

}; . . . JComboBox patternList = new JComboBox(patternExamples); patternList.setEditable(true); patternList.addActionListener(...); . . . // still use getSelectedItem() to fetch selected item even it is ent

ered by user.

Page 71: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 71

How to Use Lists

Page 72: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 72

//...where member variables are declared:

static Vector imageList; … // not limited to Strings

// Create the list of images and put it in a scroll pane

JList list = new JList(imageList); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

...

JScrollPane listScrollPane = new JScrollPane(list); possible selection modes:

SINGLE_SELECTION SINGLE_INTERVAL_SELECTION MULTIPLE_INTERVAL_SELECTION

Page 73: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 73

JList fires list selection events whenever the selection changes.

You can process these events by adding a list selection listener to the list with the addListSelectionListener method.

A list selection listener must implement one method: valueChanged.

Page 74: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 74

public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) return; JList theList = (JList)e.getSource(); if (theList.isSelectionEmpty()) { picture.setIcon(null); } else { int index = theList.getSelectedIndex(); ImageIcon newImage = new ImageIcon("images/" + (String)imageList.elementAt(index)); picture.setIcon(newImage); picture.setPreferredSize(new Dimension( newImage.getIconWidth(), newImage.getIconHeight() )); picture.revalidate(); } }

Page 75: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 75

Adding Items to and Removing Items from a List

ListModel listModel = new DefaultListModel(); listModel.addElement("Alison Huml"); listModel.addElement("Kathy Walrath"); listModel.addElement("Lisa Friendly"); listModel.addElement("Mary Campione"); list = new JList(listModel);

Page 76: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 76

public void actionPerformed(ActionEvent e) { int index = list.getSelectedIndex(); // or int[ ] getSelectedIndecies() listModel.remove(index); int size = listModel.getSize();

//Nobody's left, disable firing if (size == 0) { fireButton.setEnabled(false); //Adjust the selection } else { //removed item in last position if (index == listModel.getSize()) index--; //otherwise select same index list.setSelectedIndex(index); } }

Page 77: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 77

How to Use Menus ( with JMenu and JMenuBar)

Page 78: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 78

The Menu Component Hierarchy

Page 79: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 79

Creating Menus

//in the constructor for a JFrame subclass:

JMenuBar menuBar;

JMenu menu, submenu;

JMenuItem menuItem;

JCheckBoxMenuItem cbMenuItem;

JRadioButtonMenuItem rbMenuItem;

...

//Create the menu bar.

menuBar = new JMenuBar();

setJMenuBar(menuBar);

Page 80: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 80

//Build the first menu.

menu = new JMenu("A Menu");

menu.setMnemonic(KeyEvent.VK_A);

menu.getAccessibleContext().setAccessibleDescription(

"The only menu in this program that has menu items");

menuBar.add(menu);

//a group of JMenuItemsmenuItem = new JMenuItem("A text-only menu item", KeyEvent.VK_T);

menuItem.setAccelerator(KeyStroke.getKeyStroke(

KeyEvent.VK_1, ActionEvent.ALT_MASK));

menuItem.getAccessibleContext().setAccessibleDescription(

"This doesn't really do anything");

menu.add(menuItem);

Page 81: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 81

//a group of radio button menu items

menu.addSeparator();

ButtonGroup group = new ButtonGroup();

rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");

rbMenuItem.setSelected(true);

rbMenuItem.setMnemonic(KeyEvent.VK_R);

group.add(rbMenuItem);

menu.add(rbMenuItem);

rbMenuItem = new JRadioButtonMenuItem("Another one");

rbMenuItem.setMnemonic(KeyEvent.VK_O);

group.add(rbMenuItem);

menu.add(rbMenuItem);

Page 82: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 82

//a group of check box menu items

menu.addSeparator();

cbMenuItem = new JCheckBoxMenuItem("A check box menu item");

cbMenuItem.setMnemonic(KeyEvent.VK_C);

menu.add(cbMenuItem);

cbMenuItem = new JCheckBoxMenuItem("Another one");

cbMenuItem.setMnemonic(KeyEvent.VK_H);

menu.add(cbMenuItem);

Page 83: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 83

//a submenu menu.addSeparator(); submenu = new JMenu("A submenu"); submenu.setMnemonic(KeyEvent.VK_S); menuItem = new JMenuItem("An item in the submenu"); menuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_2, ActionEvent.ALT_MASK)); submenu.add(menuItem); menuItem = new JMenuItem("Another item"); submenu.add(menuItem); menu.add(submenu); //Build second menu in the menu bar. menu = new JMenu("Another Menu"); menu.setMnemonic(KeyEvent.VK_

N); menu.getAccessibleContext().setAccessibleDescription( "This menu does nothing"); menuBar.add(menu);

Page 84: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 84

Handling Events from Menu Items

To detect when the user selects a JMenuItem, you can listen for action events (just as you would for a JButton).

To detect when the user selects a JRadioButtonMenuItem, you can listen for either action events or item events.

For JCheckBoxMenuItems, you generally listen for item events

public class MenuDemo ... implements ActionListener,

ItemListener { ...

public void actionPerformed(ActionEvent e) {… }

public void itemStateChanged(ItemEvent e) {... }

Page 85: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 85

Bringing Up a Popup Menu

//Create the popup menu. JPopupMenu popup = new JPopupMenu(); menuItem = new JMenuItem("A popup menu item"); menuItem.addActionListener(this); popup.add(menuItem); menuItem = new JMenuItem("Another popup menu item"); menuItem.addActionListener(this); popup.add(menuItem);//Add listener to components that can bring up popup menus. MouseListener popupListener = new PopupListener(); output.addMouseListener(popupListener); menuBar.addMouseListener(popupListener); ...

Page 86: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 86

class PopupListener extends MouseAdapter {

public void mousePressed(MouseEvent e) { maybeShowPopup(e); }

public void mouseReleased(MouseEvent e) { maybeShowPopup(e); }

private void maybeShowPopup(MouseEvent e) {

if (e.isPopupTrigger()) { popup.show(e.getComponent(),

e.getX(), e.getY()); } } }

Page 87: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 87

Using Text Components

JTextComponent Hierarchy

Page 88: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 88

An Example of Using Each Text Component

Page 89: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 89

// An Example of Using a Text FieldJTextField textField = new JTextField(10);textField.setActionCommand(textFieldString);textField.addActionListener(this);//An Example of Using a Password FieldJPasswordField passwordField = new JPasswordField(10);passwordField.setActionCommand(passwordFieldString);passwordField.addActionListener(this);// Event handler for both componentspublic void actionPerformed(ActionEvent e) {… if (e.getActionCommand().equals(textFieldString)) { JTextField source = (JTextField)e.getSource(); actionLabel.setText(prefix + source.getText() + "\""); } else { JPasswordField source = (JPasswordField)e.getSource(); actionLabel.setText(prefix + new String(source.getPassword()) + "\"“ ) ; }

}

Page 90: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 90

Using Text Area

JTextArea textArea = new JTextArea(

"This is an editable JTextArea " +

"that has been initialized with the setText method. " +

"A text area is a \"plain\" text component, " +

"which means that although it can display text " +

"in any font, all of the text is in the same font."

);

textArea.setFont( new Font("Serif", Font.ITALIC, 16));

textArea.setLineWrap(true);

textArea.setWrapStyleWord(true);

Page 91: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 91

JEditorPane

the foundation for Swing's styled text components and provides the mechanism through which you can add support for custom text formats.

Using an Editor Pane to Display Text from a URL:JEditorPane editorPane = new JEditorPane();

editorPane.setEditable(false);

...//create a URL object for the TextSamplerDemoHelp.html file...

try {

editorPane.setPage(url);

} catch (IOException e) {

System.err.println("Attempted to read a bad URL: " + url);

}

Page 92: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 92

Using a Text Pane

JTextPane textPane = new JTextPane(); String[] initString = { /* ... fill array with initial text ... */ }; String[] initStyles = { /* ... fill array with names of styles ... */ };

//Create the styles we need. initStylesForTextPane(textPane); Document doc = textPane.getDocument(); //Load the text pane with styled text. try { for (int i=0; i < initString.length; i++) { doc.insertString(doc.getLength(), initString[i], textPane.getStyle(initStyles[i])); } } catch (BadLocationException ble) { System.err.println("Couldn't insert initial text."); }

Page 93: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 93

How to Use Border

Page 94: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 94

Layout components within a container

Probably different than other GUIs you’ve used All code, no resources Components are placed on panel using “layout manage

r” based on the order in which you add( ) the components

Size, shape and placement quite different depending on layout manager

Applet and application window size also affects layout

Page 95: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 95

Types of Layouts

FlowLayout BorderLayout GridLayout CardLayout GridBagLayout BoxLayout NullLayout

Page 96: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 96

FlowLayout

Components “flow” onto form left-to-right and top-to-bottom Components take on “normal” size

Page 97: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 97

The Code

Container contentPane = getContentPane();

contentPane.setLayout(new FlowLayout());

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

contentPane.add(new JButton("2"));

contentPane.add(new JButton("Button 3"));

contentPane.add(new JButton("Long-Named Button 4"));

contentPane.add(new JButton("Button 5"));

Page 98: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 98

The FlowLayout API

Three constructors: public FlowLayout() public FlowLayout(int alignment) public FlowLayout(int alignment, int horizontalGap, int verticalGap)

The alignment argument must have one of the values : FlowLayout.LEFT, FlowLayout.CENTER, FlowLayout.RIGHT.

horizontalGap and verticalGap specify the number of pixels to put between components. default gap value = 5 pixels.

Properties: Alignment, Hgap, Vgap: int, RW,

Page 99: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 99

BorderLayout

Container divided into five regions: West, North, East, South, Center.

Page 100: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 100

Example

public class BorderLayout1 extends JApplet {

public void init() {

Container cp = getContentPane();

cp.setLayout(new BorderLayout()); // default is FlowLayout

cp.add(new JButton("North") , BorderLayout.NORTH);

// cp.add(BorderLayout.NORTH, new JButton("North")); // also ok!

// cp.add(new JButton("North"), “North”); // also ok!

cp.add(BorderLayout.SOUTH, new JButton("South"));

cp.add(BorderLayout.EAST, new JButton("East"));

cp.add(BorderLayout.WEST, new JButton("West"));

cp.add(BorderLayout.CENTER, new JButton("Center"));

} } Default for most things

Page 101: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 101

Additional properties of BorderLayout

(Horizontal and Vertical ) Gaps between components constructor:

BorderLayout(int hgap, int vgap)

methods: void setHgap(int) void setVgap(int)

Page 102: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 102

GridLayout

Organized in rows & columns

Page 103: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 103

The code

Container contentPane = getContentPane();

contentPane.setLayout(new GridLayout(3,2));

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

contentPane.add(new JButton("2"));

contentPane.add(new JButton("Button 3"));

contentPane.add(new JButton("Long-Named Button 4"));

contentPane.add(new JButton("Button 5")); APIs:

public GridLayout(int rows, int columns [, int hgap, int vgap ])

Page 104: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 104

CardLayout Use JTabbedPane instead. import java.awt.*; public class main extends JApplet implement ActionListner { CardLayout cards = new CardLayout(); JButton b1 = new JButton(“one”), …, b3 = new JButton(“three”); b1.addActionListner( this); … ; b3.addActionListner(this) public void init() { setLayout( cards ); add( new Button("one"), "one" ); add( new Button("two"), "two" ); add( new Button("three"), "three" ); } public void actionPerformed( ActionEvent e) { // flip to next card! cards.next( this ); } }

Page 105: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 105

CardLayout API

void first(Container) void next(Container) void previous(Container) void last(Container) void show(Container, String cardID)

show card identified by cardID.

Page 106: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 106

GridBagLayout

Flexible layout manager that aligns components horizontally and vertically, without requiring that the components be the same size

Quite a mess to program Must use GridBagConstraints This is what happens without resources

You can accomplish a lot by combining other layout managers.

To make it easier, Swing has BoxLayout

Page 107: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 107

BoxLayout

Place all components in a row or in a column. Much of the benefit of GridBagLayout without the pain Has helper class Box which uses BoxLayout and builds compon

ents for you

Page 108: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 108

BoxLayout

Page 109: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 109

South

Center

JPanel(BoxLayout(V))

label

rigidArea(0,5)

JScrollPane

JButton JButtonHorizontalGlue

rigidArea(10,0)JPanel (BorderLayout)

The Layout structure

JPanel(BoxLayout(H))

Page 110: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 110

The Code

JScrollPane listScroller = new JScrollPane(list); listScroller.setPreferredSize(new Dimension(250, 80)); listScroller.setMinimumSize(new Dimension(250, 80)); listScroller.setAlignmentX(LEFT_ALIGNMENT); ... //Lay out the label and scroll pane from top to bottom. JPanel listPane = new JPanel(); listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS)); JLabel label = new JLabel(labelText); listPane.add(label); listPane.add(Box.createRigidArea(new Dimension(0,5))); listPane.add(listScroller); listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));

Page 111: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 111

// Lay out the buttons from left to right.

JPanel buttonPane = new JPanel();

buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));

buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));

buttonPane.add(Box.createHorizontalGlue());

buttonPane.add(cancelButton);

buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));

buttonPane.add(setButton);

// Put everything together, using the content pane's BorderLayout.

Container contentPane = getContentPane();

contentPane.add(listPane, BorderLayout.CENTER);

contentPane.add(buttonPane, BorderLayout.SOUTH);

Page 112: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 112

Box Layout Features

the box layout takes the components‘ alignments and minimum, preferred, and maximum sizes into account.

Respect each component's requested minimum and maximum heights.

Use preferred height ( or weight ) as default. layout principles:

tries to make all of its container's components equally wide -- as wide as the largest preferred width.

container wider => make all the components as wide as the container. If the components aren't all the same width then X alignment comes in

to play.

Page 113: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 113

Container wider than maximumSize

All components’s AllignmentX are LEFT_ALLIGNMENT(0.0) All components’s AllignmentX are CENTER_ALLIGNMENT(0.5) All components’s AllignmentX are RIGHT_ALLIGNMENT(1.0)

Page 114: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 114

Components have different allignmentXs: 0.0, 0.5, 1.0.

Page 115: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 115

When no component has maximumSize

same allignmentX => made as wide as their container. different allignmentX :

components with an X alignment of 0.0 (left) or 1.0 (right) will be smaller.

components with an intermediate X alignment will be as wide as their container

Page 116: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 116

Using Invisible Components as Filler

to have space between components: add an empty border to one or both components, or insert invisible components to provide the space. use Box class to create invisible components.

Creating invisible components with Box and Box.Filler.

Type SizeConstraint HowToCreate

rigidArea Box.createRigidArea(size)

glue

horizontal Box.createHorizontalGlue()

vertical Box.createVerticalGlue()

custom Box.Filler new Box.Filler(minSize, prefSize, maxSize)

Page 117: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 117

Rigid area

Use this when you want a fixed-size space between two components.

container.add(firstComponent); container.add(Box.createRigidArea(new Dimension(5,0))); container.add(secondComponent);

Page 118: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 118

Glue

container.add(firstComponent); container.add(Box.createHorizontalGlue()); container.add(secondComponent);

Page 119: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 119

Custom Box.Filler

// ensure 5~100 pixels b/t components and 100 px height

container.add(firstComponent);

Dimension minSize = new Dimension(5, 100);

Dimension prefSize = new Dimension(5, 100);

Dimension maxSize = new Dimension(Short.MAX_VALUE, 100);

container.add(new Box.Filler(minSize, prefSize, maxSize));

container.add(secondComponent);

Page 120: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 120

Specifying Component Sizes

change the minimum, preferred, and maximum sizes in two ways:

Invoking setXxxSize method ( defined by the JComponent class). comp.setMinimumSize(new Dimension(50, 25)); comp.setPreferredSize(new Dimension(50, 25)); comp.setMaximumSize(new Dimension(Short.MAX_VALUE, Short.MA

X_VALUE )); Overriding getXxxSize method:

...//in a subclass of a component class: public Dimension getMaximumSize() { size = getPreferredSize(); size.width = Short.MAX_VALUE; return size; }

Page 121: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 121

The Box and BoxLayout API Constructors:

BoxLayout(Container, int axis) Box(int axies) // create a Box : subclass of Container but not JComponent static Box createHorizontalBox() // = new Box(BoxLayout.X_AXIS) static Box createVerticalBox()

Constructors or methods creating Space Fillers Component createRigidArea(Dimension) Create a rigid lightweight component. Component createHorizontalGlue() Component createVerticalGlue() Component createGlue() Create a glue lightweight component. Horizontal glue and vertical glue can be very useful. Component createHorizontalStrut() Component createVerticalStrut() Create a "strut" lightweight component. We recommend using rigid areas instead of struts. Box.Filler(Dimension, Dimension, Dimension)

Page 122: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 122

Null Layout (absolute Positioning)

setLayout(null); Programmers are responsible for setting the size and position o

f each component. ( via setBounds(x, y, witdth, height))

Page 123: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 123

The code

public class NoneWindow extends JFrame { . . . private boolean laidOut = false; private JButton b1, b2, b3; public NoneWindow() { Container contentPane = getContentPane(); contentPane.setLayout(null);

b1 = new JButton("one"); contentPane.add(b1); b2 = new JButton("two"); contentPane.add(b2); b3 = new JButton("three"); contentPane.add(b3); Insets insets = contentPane.getInsets(); b1.setBounds(25 + insets.left, 5 + insets.top, 75, 20); b2.setBounds(55 + insets.left, 35 + insets.top, 75, 20); b3.setBounds(150 + insets.left, 15 + insets.top, 75, 30); . . . } . . . }

Page 124: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 124

Event Handling

Not limited to ActionListener InputEvent: KeyEvent, MouseEvent, MouseMotionEvent, ContainerEvent, ComponentEvent,…

Each type of event represented by a class Component responds to an event by making an event object an

d calling each “listener” registered for that event An event listener implements a particular listener interface usin

g an inner class addXXXListener( ) adds a listener to your component, removeX

XXListener( ) un-registers it

Page 125: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 125

Java Event Model

delegation ( or forwarding ) model

l:EventListner

b:EventSource

system:

l = new EventListener(…)

b=new EventSource(…)

addXXXListener(l) Event e1 occurs

doXXXAction(e1)

Event e2 occurs

doXXXAction(e2)

….

Page 126: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 126

Event, listener interface and add-and

remove-methods

Components supporting this event

ActionEvent

ActionListener ; addActionListener( )

removeActionListener( )

Button, List, TextField, MenuItem, CheckboxMenuItem, Menu and PopupMenu

AdjustmentEvent

AdjustmentListener ; addAdjustmentListener( )

removeAdjustmentListener( )

Scrollbar, Anything you create that implements Adjustable

ComponentEvent

ComponentListener

addComponentListener( )

removeComponentListener( )

Component and its derivatives, including Button, Canvas, Checkbox, Choice, Container, Panel, Applet, ScrollPane,Window,Dialog,FileDialog,Frame,Label,List, Scrollbar, TextArea and TextField

Page 127: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 127

Event, listener interface and add-and

remove-methods

Components supporting this event

ContainerEvent

ContainerListener

addContainerListener( )

removeContainerListener( )

Container and its derivatives, including Panel, Applet, ScrollPane, Window, Dialog, FileDialog and Frame

FocusEvent

FocusListener

addFocusListener( )

removeFocusListener( )

Component and its derivatives, including Button, Canvas, Checkbox, Choice,

Container, Panel, Applet, ScrollPane,

Window, Dialog, FileDialog, Frame Label,

List, Scrollbar, TextArea and TextField

KeyEvent

KeyListener

addKeyListener( )

removeKeyListener( )

Component and its derivatives, including Button, Canvas, Checkbox, Choice,

Container, Panel, Applet, ScrollPane,

Window,Dialog,FileDialog,Frame,Label,

List, Scrollbar, TextArea and TextField

Page 128: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 128

Event, listener interface and add-and

remove-methods

Components supporting this event

MouseEvent (for both clicks and motion)

MouseListener;

addMouseListener( )

removeMouseListener( )

Component and its derivatives, including Button, Canvas, Checkbox, Choice,

Container, Panel, Applet, ScrollPane,

Window,Dialog,FileDialog,Frame,Label,

List, Scrollbar, TextArea and TextField

MouseEvent (for both clicks and motion)

MouseMotionEvent

MouseMotionListener

addMouseMotionListener( )

removeMouseMotionListener( )

Component and its derivatives, including Button, Canvas, Checkbox, Choice,

Container, Panel, Applet, ScrollPane,

Window,Dialog,FileDialog,Frame,Label,

List, Scrollbar, TextArea and TextField

WindowEvent

WindowListener

addWindowListener( )

removeWindowListener( )

Window and its derivatives, including Dialog, FileDialog, Frame, JFrame,

Page 129: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 129

Event type: ItemEvent listener interface: ItemListener add-and-remove-methods : addItemListener( ), removeItemLi

stener( ) Components supporting this event : Checkbox, CheckboxMe

nuItem, Choice, List and anything that implements ItemSelectable.

Event type: TextEvent listener interface: TextListener add-and-remove-methods : addTextListener( ), removeTextLi

stener( ) Components supporting this event :Anything derived from T

extComponent, including TextArea and TextField

Page 130: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 130

Subinterfaces of EventListner and their methods Listener interface/ adapter Methods in interface ActionListener actionPerformed(ActionEvent) AdjustmentListener adjustmentValueChanged(AdjustmentEven

t)

ComponentListener, componentHidden(ComponentEvent)

ComponentAdapter componentShown(ComponentEvent)

componentMoved(ComponentEvent)

componentResized(ComponentEvent)

ContainerListener, componentAdded(ContainerEvent)

ContainerAdapter componentRemoved(ContainerEvent) FocusListener, focusGained(FocusEvent) // get keyboard

FocusAdapter focusLost(FocusEvent) // lost keyboard

Page 131: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 131

Subinterfaces of EventListner and their methods

Listener interface w/ adapter Methods in interface KeyListener, keyPressed(KeyEvent)

KeyAdapter keyReleased(KeyEvent)

keyTyped(KeyEvent)

MouseListener, mouseClicked(MouseEvent)

MouseAdapter mouseEntered(MouseEvent)

mouseExited(MouseEvent)

mousePressed(MouseEvent)

mouseReleased(MouseEvent)

MouseMotionListener, mouseDragged(MouseEvent) MouseMotionAdapter mouseMoved(MouseEvent)

Page 132: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 132

Subinterfaces of EventListner and their methods

Listener interface w/ adapter Methods in interface

WindowListener, windowOpened(WindowEvent)

WindowAdapter windowClosing(WindowEvent)

windowClosed(WindowEvent)

windowActivated(WindowEvent)

windowDeactivated(WindowEvent)

windowIconified(WindowEvent)

windowDeiconified(WindowEvent)

ItemListener itemStateChanged(ItemEvent) TextListener textValueChanged(TextEvent)

Page 133: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 133

And more in Swing:

AncestorListner CaretListner, CellEditorListner ChangeListner HyperlinkListner InternalFrameListner ListDataListner ListSelectionListner MenuDragMouseListner, MenuKeyListner,,MenuListner PopupMenuListner TreeExpansionListner, TreeSelectionListner, TreeWillExpand

Listner java.bean.propertyChangeListner, vetoableChangeListner

Page 134: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 134

JavaBeans

Component programming model True power in visual programming Must be able to instantiate, query and configure objects

at design time Java 1.1 reflection provides method and field

information on a live object Methods, arguments, return values

Beans specifies a naming convention Identifies design-time fields, event handlers

Page 135: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 135

What is a Bean?

Just a class (thus easy to learn & use) Supports three concepts:

Properties Events Methods

Follows naming convention to identify these Java call this convention a “design pattern”

Page 136: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 136

Properties, Methods, Events

For a property named xxxx of type T, create two methods: pubic T getXxxx( ) // capitalize the first char public void setXxxx(T ). (First letter automatically capitalized). boolean property: may also use “is” instead of “get.” boolean isXxxx() Ordinary methods are public

Events use the same “Listeners,” with add- and remove- methods like before

You can create your own event types

Page 137: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 137

A Simple Bean

class Spots {}public class Frog { private int jumps; private Color color; private Spots spots; private boolean jmpr; public int getJumps() { return jumps; } public void setJumps(int js) { jumps = js; } public Color getColor() { return color; } public void setColor(Color c) { color = c; } public Spots getSpots() { return spots; } public void setSpots(Spots newSpots) { spots = newSpots; }

Page 138: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 138

public boolean isJumper() { return jmpr; }

public void setJumper(boolean j) { jmpr = j; }

public void addActionListener(ActionListener l) { //...

}

public void removeActionListener(ActionListener l) { // ...

}

public void addKeyListener(KeyListener l) { // ...

}

public void removeKeyListener(KeyListener l) { // ...

}

// An "ordinary" public method:

public void croak() { System.out.println("Ribbet!"); }

}

Page 139: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 139

Introspection

Introspector automatically analyzes a Bean for properties, events & methods

Page 140: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 140

Summary

“Listener” event model and Beans are a big step forward

Swing is the best UI library I’ve seen All Swing components are JavaBeans Numerous application builders use Beans Beans enable RAD environments Beans support more sophistication than shown here

Page 141: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 141

Summary

Java GUI has gone through a lot of design changes Enough of an intro to get you started Use a GUI builder for serious development Other references:

“Core Java 2” by Horstmann & Cornell, Prentice-Hall Online help

Page 142: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 142

Problem 4

1. Create an JFrame with a text field and 3 buttons. When you press each button, make some different text appear in the text field.

2. Add a check box to your JFrame,capture the event and insert different text into the text field.

3. Add a set of radio buttons which change the text in the text field.

4. Add a menu that changes the text field when any of its menu item is selected.

Page 143: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 143

Page 144: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 144

More Java topics …

Not detailed: JDBC, RMI, JavaBeans advanced Swing :Jtree, JTable, JText,…

Not covered: Java Security model Internationalization ( i18n, l10n ) Native Methods, Java 2D, Java 3D, Java mulitmedia framework (JMF) XML, JavaMail

J2EE: JDBC, RMI, Servlet and JavaServer page, java IDL (Corba), Java Transaction service

(JTS), RMI over IIOP, Java Message Queue(JMQ), JNDI, Enterprise JavaBeans

J2ME: KVM, Configuration: CLDP, profile: MIDP

Page 145: Java Programming Transparency No. 1 Lecture 9 Java GUI Cheng-Chia Chen

Java GUI

Transparency No. 145

J2ME

Java 2 platform targeted at consumer electronics and embedded devices.

consists of a virtual machine ( KVM, thirdParty: Colored KVM, J9 ) and a set of APIs suitable for providing tailored runtime environments for

consumer and embedded electronics. two primary kinds of components

Configurations: low-level APIs and optimized virtual machines targeted at two broad categories of devices:

180K ~512K(CLDC: Connection limited device configuration), and 512K+

profile: a specification that details the JavaTM technology APIs, built on top of and utilizing the underlying Configuration, necessary to provide a complete runtime environment for a specific kind of device.

Known profiles: MIDP (Mobile Information Device profile)