Copyright © 2003 Pearson Education, Inc. Slide 7-1 Problem Solving with Java™ Second Edition...

53
Copyright © 2003 Pearson Education, Inc. Slide 7-1 Problem Solving with JavaSecond Edition Elliot Koffman and Ursula Wolz Copyright © 2003 Pearson Education, Inc. Prepared by: Elliot Koffman, Temple University and Dorina Petriu, Carleton University
  • date post

    19-Dec-2015
  • Category

    Documents

  • view

    219
  • download

    3

Transcript of Copyright © 2003 Pearson Education, Inc. Slide 7-1 Problem Solving with Java™ Second Edition...

Copyright © 2003 Pearson Education, Inc. Slide 7-1

Problem Solving with Java™Second Edition

Elliot Koffman and Ursula Wolz

Copyright © 2003 Pearson Education, Inc.

Prepared by: Elliot Koffman, Temple University and Dorina Petriu, Carleton University

Copyright © 2003 Pearson Education, Inc. Slide 7-2

Chapter 7

Graphical User Interfaces (GUIs)

Copyright © 2003 Pearson Education, Inc. Slide 7-3

Chapter Outline

• 7.1 AWT, Swing, and Browser-Applet Interaction

• 7.2 Designing a First GUI

• 7.3 The Java Event Model

• 7.4 Using a GUI in an Application

• 7.5 Components for Making Choices

• 7.6 Designing a GUI for an Existing Class

• Case Study: A GUI for the PhoneBook Class

• 7.7 Listener Classes as Inner Classes

• 7.8 Layout Managers

Copyright © 2003 Pearson Education, Inc. Slide 7-4

7.1 AWT, Swing, and Browser-Applet Interaction

AWT SwingJava 1.0, 1.1 Java 1.2, 2.0

Component appearance isplatform dependent - sameform as other GUI componentsfor platform

Component appearance isplatform independent - look issame regardless of platform

Components are drawn bycorresponding componentsprovided by platform'soperating system (peercomponents).

Components are drawn by Javamethods (lightweightcomponents).

Copyright © 2003 Pearson Education, Inc. Slide 7-5

Kinds of classes used in AWT and Swing

Kind of class UseSwing GUIcomponent classes

Represent basic window objects like buttons, textfields, menu items. Also includes panels andapplets which act as containers (groupings) forthe basic window objects.

AWT Layoutmanager classes

Determine the placement of objects in a container

AWT Event classes Define the events that are generated when usersclick buttons, select menu items, and move themouse.

AWT Listener classes Contain methods that are activated by theoperating system when events occur.

Copyright © 2003 Pearson Education, Inc. Slide 7-6

Part of AWT and Swing Hierarchy

Copyright © 2003 Pearson Education, Inc. Slide 7-7

Components of a GUI (applet DistanceGUI.java)

labelJLabel

text fieldJTextField

buttonJButton

text areaJTextArea

buttonJButton

Copyright © 2003 Pearson Education, Inc. Slide 7-8

HTML file to load applet DistanceGUI

<HTML><TITLE>Distance Conversion Applet </TITLE><applet code = DistanceGUI.class width = 300 height = 200></applet> </HTML>

Copyright © 2003 Pearson Education, Inc. Slide 7-9

Methods called by browser

Method Purpose

init() Initializes the applet. Programmer override this method

when writing an applet.

start() Makes the applet “active”; that is, it starts the applet

running. Programmer does not override this method.

stop() Makes the applet “inactive”; that is, it stops the applet.

Programmer does not override this method.

destroy() Destroys the applet so that its resources can be recycled.

The browser calls this method when the user exits the

applet context.

Programmer does not override this method.

Copyright © 2003 Pearson Education, Inc. Slide 7-10

Applet-browser interaction

Copyright © 2003 Pearson Education, Inc. Slide 7-11

7.2 GUI Design

An interface enables a user to interact with a program or machine (for example, an ATM). An interface provides: instructions or information for the user (labels,

text fields, text areas) a way for the user to provide input to the device

(textfields, buttons, pull-down lists, menus) an area for the device to display outputs (text

areas) a way for the user to control the interaction with

the device (buttons)

Copyright © 2003 Pearson Education, Inc. Slide 7-12

Containers in our first GUI

JAppletDistanceGUI

JPaneldataPanel

JPanelbuttonPanel

Copyright © 2003 Pearson Education, Inc. Slide 7-13

Containment hierarchy for applet DistanceGUI

Copyright © 2003 Pearson Education, Inc. Slide 7-14

Class DistanceConverter methods for conversion

public class DistanceConverter { // Data field private static final double CONVERT_FACTOR = 1.609;

// Methods // precondition: A distance in kilometers is passed as // an argument. // postcondition: Returns the equivalent value in miles public double toMiles(double kms) { return kms / CONVERT_FACTOR; }

// precondition: A distance in miles is passed as an // argument. // postcondtion: Returns the equivalent value in kms. public double toKilometers(double miles) { return miles * CONVERT_FACTOR; } }

Copyright © 2003 Pearson Education, Inc. Slide 7-15

Class DistanceGUI

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

public class DistanceGUI extends JApplet implements ActionListener { // Data fields private JTextField input = new JTextField(10); private JTextArea output = new JTextArea(2, 20); private JButton toKms = new JButton("Convert to kms"); private JButton toMiles = new JButton("Convert to miles");

// Methods // postcondition: Overrides JApplet init() method. public void init() { // Declare local variables JLabel inputLab = new JLabel("Input distance >>"); JPanel dataPanel = new JPanel(); JPanel buttonPanel = new JPanel();

// Define the layout manager for the applet getContentPane().setLayout(new FlowLayout());

// Fill dataPanel and add it to applet dataPanel.add(inputLab); dataPanel.add(input); getContentPane().add(dataPanel);

Interface forevent listeners

API forJava events

Copyright © 2003 Pearson Education, Inc. Slide 7-16

Class DistanceGUI, cont’d.

// Give the focus (cursor) to the input text field input.requestFocus();

// Fill buttonPanel and add it to applet buttonPanel.add(toKms); buttonPanel.add(toMiles); getContentPane().add(buttonPanel);

// Add output text area to applet getContentPane().add(output);

// Register applet as listener for button presses toMiles.addActionListener(this); toKms.addActionListener(this); } // end init

// Insert method actionPerformed(), slide 21 (Fig. 7.12)

Copyright © 2003 Pearson Education, Inc. Slide 7-17

Constructors in class DistanceGUIConstructor Behavior

JTextField(String str, int col)

Example: JTextField(10)

Creates an editable text field with col columns andString str as its initial contents. Either or botharguments may be omitted. The defaults are nulland 0. If the dimension argument is omitted, thewidth will be determined by the string argument.

JTextArea(String str, int row, int col)

Example: JTextArea(2, 20)

Creates an editable text area with row rows andcol columns and string str as its initial contents.Either the string or both dimension arguments maybe omitted. The defaults are null and 0. If thedimension arguments are omitted, the text area willfit the string argument.

JButton(String str, Icon pic)

Example:JButton("Convert to miles")

Creates a "push" button showing the text in strand the image in file pic. Either or both argumentsmay be omitted. The defaults are null.

JLabel(String str, Icon pic)

Example:JLabel("Input distance >>")

Creates a display area for the text in string str orthe image in file pic. Either or both argumentsmay be omitted. The defaults are null.

JPanel(LayoutManager lM)

Example:JPanel(new BorderLayout())

Creates a new container for components using thelayout specified by its argument. The argumentmay be omitted. The default for a panel isFlowLayout.

Copyright © 2003 Pearson Education, Inc. Slide 7-18

Methods called from init()Method Calls in init() Behavior

container.setLayout( LayoutManager lM);

Example:getContentPane().setLayout( new FlowLayout());

Sets the layout manager for thecontainer to which it is applied to thelayout manager object lM. Each ofJava's layout manager classesimplements the interfaceLayoutManager.

container.add(Component c);

Examples:dataPanel.add(input);getContentPane().add(dataPanel);

Adds component c to the containerwhose add() method is called. Eachof Swing's atomic components is asubclass of Component.

component.requestFocus();

Example: input.requestFocus();

Gives the focus (the input cursor) tothe object that receives this message.

generator.addActionListener( ActionListener listener);

Example:toMiles.addActionListener(this);

The listener object is registered.as alistener for events generated by thegenerator object. If the argument isthis, the applet object is the listener.

Copyright © 2003 Pearson Education, Inc. Slide 7-19

7.3 The Java Event Model

An event generator initiates an event (an object of some Event type). Many GUI components are event generators. For example, a button has a visual representation on the screen. When a mouse click occurs within the area of the button, some action should take place in a program. The “button press” generates an “action event.”

An event listener is an object that listens for, and then responds to events of a particular type. For example, the applet (an object created by the browser) will typically respond to action events generated by its buttons.

Java Event Model button toMiles an action event the applet

/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\ ( object dGUI )generates action events listens for and responds to

events generated by toMiles button

Convert to kms

Copyright © 2003 Pearson Education, Inc. Slide 7-20

The ActionListener interface• A listener of action events must be type ActionListener. Type DistanceGUI objects extend class JApplet. Since most AWT and Swing classes already extend some other class, the ActionListener type is an interface and the heading for class DistanceGUI indicates that it implements class ActionListener.

public class DistanceGUI extends JApplet implements ActionListener {

• Registering event listenersCall a button's addActionListener( ) method to register the method argument (this applet) as a listener for action events generated by that button. These statements have the form:

generatorObject.addActionListener(listenerObject);

• Registering an applet as an event listener toMiles.addActionListener(this); toKms.addActionListener(this);this applet is registered as a listener for action events generated by its buttons.

Copyright © 2003 Pearson Education, Inc. Slide 7-21

DistanceGUI method actionPerformed()

// precondition: Text field input contains numeric // information. // postcondition: Performs the conversion requested by // user, placing the result in text area output. public void actionPerformed(ActionEvent aE) { String inputStr = input.getText(); double inputDist = Double.parseDouble(inputStr); double outputDist; DistanceConverter dC = new DistanceConverter(); Object buttonPressed = aE.getSource(); if (buttonPressed == toMiles) { outputDist = dC.toMiles(inputDist); output.setText(inputDist + " kilometers converts to\n" + outputDist + " miles"); } else if (buttonPressed == toKms) { outputDist = dC.toKilometers(inputDist); output.setText(inputDist + " miles converts to\n" + outputDist + " kilometers"); } input.requestFocus(); // Gives the focus to input } }

Returns referenceto event generator

Copyright © 2003 Pearson Education, Inc. Slide 7-22

7.4 Using a GUI in an application

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

public class DistanceGUIApp {

public static void main(String[] args) { // Create a JFrame object JFrame frame = new JFrame(); frame.setSize(300, 200); frame.setTitle("Distance Conversion"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // Create a DistanceGUI object - add it to frame. JApplet dGUI = new DistanceGUI(); frame.getContentPane().add(dGUI);

// Start dGUI and make frame "visible". dGUI.init(); dGUI.start(); frame.setVisible(true); }}

Method 1: Instantiate applet DistanceGUI and place it in a frame.

Copyright © 2003 Pearson Education, Inc. Slide 7-23

Class DistanceGUIFrame

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

public class DistanceGUIFrame extends JFrame implements ActionListener { // Data fields private JTextField input = new JTextField(10); private JTextArea output = new JTextArea(2, 20); private JButton toKms = new JButton("Convert to kms"); private JButton toMiles = new JButton("Convert to miles");

// Methods public DistanceGUIFrame() { // Declare local variables JLabel inputLab = new JLabel("Input distance >>"); JPanel dataPanel = new JPanel(); JPanel buttonPanel = new JPanel();

// Define the layout manager for the applet getContentPane().setLayout(new FlowLayout());

// Fill dataPanel and add it to applet dataPanel.add(inputLab); dataPanel.add(input); getContentPane().add(dataPanel);

// . . .

Subclass of JFrame

Replace init()with constructor

Method 2: Rewrite applet DistanceGUI as frame DistanceGUIFrame.

Copyright © 2003 Pearson Education, Inc. Slide 7-24

Method main() for class DistanceGUIFrame

// Creates the frame and closes the frame.public static void main(String[] args) { DistanceGUIFrame dGUI = new DistanceGUIFrame(); dGUI.setSize(300, 200); dGUI.setVisible(true); dGUI.setTitle("Distance Conversion"); dGUI.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } } );}

Exit program whenuser closes frame.

Copyright © 2003 Pearson Education, Inc. Slide 7-25

7.5 Components for making choices

checkboxes

radiobuttons

Copyright © 2003 Pearson Education, Inc. Slide 7-26

Class CheckBoxDemo

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

public class CheckBoxDemo extends JApplet implements ItemListener { private JCheckBox temp1 = new JCheckBox("cold"); private JCheckBox temp2 = new JCheckBox("mild"); private JCheckBox temp3 = new JCheckBox("hot"); private JCheckBox precip1 = new JCheckBox("dry"); private JCheckBox precip2 = new JCheckBox("wet"); private JCheckBox precipKind1 = new JCheckBox("rain"); private JCheckBox precipKind2 = new JCheckBox("snow"); private JCheckBox precipKind3 = new JCheckBox("mix"); private JTextArea weather = new JTextArea(8, 20);

// postcondition: Builds a GUI with check boxes in 3 panels. public void init() { // . . .

// Register the applet as an item listener for all // check boxes temp1.addItemListener(this); temp2.addItemListener(this); temp3.addItemListener(this); precip1.addItemListener(this); precip2.addItemListener(this); precipKind1.addItemListener(this); precipKind2.addItemListener(this); precipKind3.addItemListener(this); }

item listeners respondto check box events

Copyright © 2003 Pearson Education, Inc. Slide 7-27

Class CheckBoxDemo, cont’d.

// postcondition: Displays information about weather conditions // selected by check boxes in output text area. public void itemStateChanged(ItemEvent e) { String weatherStr = "Here are the weather conditions:\n"; if (temp1.isSelected()) weatherStr += "cold\n"; if (temp2.isSelected()) weatherStr += "mild\n"; if (temp3.isSelected()) weatherStr += "hot\n"; if (precip1.isSelected()) weatherStr += "dry\n"; if (precip2.isSelected()) weatherStr += "wet\n"; if (precipKind1.isSelected()) weatherStr += "rain\n"; if (precipKind2.isSelected()) weatherStr += "snow\n"; if (precipKind3.isSelected()) weatherStr += "mix of snow and rain\n"; weather.setText(weatherStr); }}

Is check boxprecip1 “on”?

Copyright © 2003 Pearson Education, Inc. Slide 7-28

Class RadioButtonDemo

public class RadioButtonDemo extends JApplet implements ActionListener { private JRadioButton[] temp = {new JRadioButton("cold"), new JRadioButton("mild"), new JRadioButton("hot")};

private JRadioButton[] precip = {new JRadioButton("dry"), new JRadioButton("wet")};

private JRadioButton[] precipKind = {new JRadioButton("clear"), new JRadioButton("rain"), new JRadioButton("snow"), new JRadioButton("mix")}; private JTextArea weather = new JTextArea(8, 20);

public void init() { // Define the layout manager for the applet getContentPane().setLayout(new FlowLayout());

// Define panel & button group for temperature radio buttons, // add each button to panel and to button group and // register applet as a listener for each button, JPanel tempPanel = new JPanel(); ButtonGroup tempGr = new ButtonGroup(); for (int butNum = 0; butNum < temp.length; butNum++) { tempPanel.add(temp[butNum]); tempGr.add(temp[butNum]); temp[butNum].addActionListener(this); } getContentPane().add(tempPanel);

action listeners respondto radio button events

only one buttonin a group can

be selected

Copyright © 2003 Pearson Education, Inc. Slide 7-29

Class RadioButtonDemo, cont’d.

// Define panel and button group for // precipitation radio buttons, // add each button to panel and to button group and // register applet as a listener for each button, JPanel precipPanel = new JPanel(); ButtonGroup precipGr = new ButtonGroup(); for (int butNum = 0; butNum < precip.length; butNum++) { precipPanel.add(precip[butNum]); precipGr.add(precip[butNum]); precip[butNum].addActionListener(this); } getContentPane().add(precipPanel);

// Define panel and button group for // precipitation kind radio buttons, // add each button to panel and to button group and // register applet as a listener for each button, JPanel precipKindPanel = new JPanel(); ButtonGroup precipKindGr = new ButtonGroup(); for (int butNum = 0; butNum < precipKind.length; butNum++) { precipKindPanel.add(precipKind[butNum]); precipKindGr.add(precipKind[butNum]); precipKind[butNum].addActionListener(this); } getContentPane().add(precipKindPanel); // Add the output text area to the applet getContentPane().add(weather); }

Copyright © 2003 Pearson Education, Inc. Slide 7-30

Class RadioButtonDemo, cont’d.

public void actionPerformed(ActionEvent e) { String weatherStr = "Here are the weather conditions:\n"; for (int butNum = 0; butNum < temp.length; butNum++) { if (temp[butNum].isSelected()) weatherStr += (temp[butNum].getText() + "\n"); }

for (int butNum = 0; butNum < precip.length; butNum++) { if (precip[butNum].isSelected()) weatherStr += (precip[butNum].getText() + "\n"); }

for (int butNum = 0; butNum < precipKind.length; butNum++) { if (precipKind[butNum].isSelected()) weatherStr += (precipKind[butNum].getText() + "\n"); }

weather.setText(weatherStr); }}

Copyright © 2003 Pearson Education, Inc. Slide 7-31

Combo box

• A combo box (type JComboBox) allows the user to select one of several options and is used to represent a drop-down list. For example, a combo box can be used to allow a user to select one title from among several (Mr., Ms., Mrs., Dr.) or to select your state of residence from among the 50 possible choices.

• Making a selection generates an item event. – Apply method getSelectedIndex() to return the index of the selected

item, starting with 0 for the first option in the drop-down list.– Apply method getSelectedItem() to return the selected item (type

Object).

• Initialize a combo box's options through an array of strings. Use method addItem() to add individual options (strings). When the combo box is initially displayed, the first option will be shown.

Copyright © 2003 Pearson Education, Inc. Slide 7-32

Class ComboBoxDemo

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

public class ComboBoxDemo extends JApplet implements ItemListener {

private JComboBox titleList; private JTextField greeting = new JTextField(20);

// Creates a GUI with a combo box for selecting a title // and a text field for output. public ComboBoxDemo() { getContentPane().setLayout(new FlowLayout()); String titles[] = {"Mr.", "Ms.", "Mrs.", "Dr."}; titleList = new JComboBox(titles); titleList.addItem("Professor"); getContentPane().add(titleList); getContentPane().add(greeting); titleList.addItemListener(this); }

// postcondition: Displays a greeting that includes the title // selected from the combo box. public void itemStateChanged(ItemEvent itEv) { if (itEv.getSource() == titleList) { String titleStr = (String) titleList.getSelectedItem(); greeting.setText("Dear " + titleStr + " Jones;"); } }}

Retrieve objectselected andcast to String

Copyright © 2003 Pearson Education, Inc. Slide 7-33

Sample run of class ComboBoxDemo

pull down

list

Copyright © 2003 Pearson Education, Inc. Slide 7-34

7.6 Designing a GUI for an existing classset get

number on

Select Aaron Mckie

Showresult

Copyright © 2003 Pearson Education, Inc. Slide 7-35

Description of PhoneBookGUI classData fieldsJTextField nameTextJTextField numberTextJRadioButton addRBJRadioButton getRBJRadioButton changeRBJTextArea instructJComboBox nameListJButton submitPhoneBook myPhoneBook

Methodsvoid init()void actionPerformed()

void itemStateChanged()

Classes UsedPhoneBook, Friend, String, JTextField, JRadioButton, JTextArea, JComboBox, ButtonGroup, JApplet, ItemListener, ActionListener

Attributes•A name•A phone number•Radio button for adding a friend•Radio button for getting a number•Radio button for changing a number•Text area for displaying instructions and results•Combo box for selecting a name•A button to initiate processing an operation•A phone book object

Behavior•Creates a GUI object.•Responds to action events generated by pressing a radio button or the submit button.•Responds to item events generated by making a selection from the combo box.

Copyright © 2003 Pearson Education, Inc. Slide 7-36

Algorithm for init()

1. Set the layout manager to flow layout.2. Place the radio buttons in a panel and in a button group and

add the panel. 3. Add the data area for displaying instructions.4. Place the name and number text fields in a panel and add the

panel.5. Place the combo box and submit button in a panel and add

the panel.6. Register the applet as an action listener for all buttons and as

an item listener for the combo box.

Copyright © 2003 Pearson Education, Inc. Slide 7-37

Algorithms for listener methods

1. if a radio button is pressed Display instructions for performing the selected operation.

else if submit is pressed and add entry is selectedGet the friend's name and number, add the friend to the directory, and add the friend's name to the combo box selection list.

else if submit is pressed and get number is selectedGet the friend's name and retrieve the friend's number from the directory.

else if submit is pressed and change number is selectedGet the friend's name and new number.if the friend is in the directory

Replace the entry at that location with one containing the friend's name and new number.

elseDisplay an error message.

Algorithm for actionPerformed()

Algorithm for itemStateChanged()

1. if a name is selected from the combo box listStore the name selected in data field nameText..

Copyright © 2003 Pearson Education, Inc. Slide 7-38

PhoneBookGUI data fields and method init()

public class PhoneBookGUI extends JApplet implements ActionListener, ItemListener { private JTextField nameText = new JTextField(10); private JTextField numberText = new JTextField(10); private JRadioButton addRB = new JRadioButton("add entry"); private JRadioButton getRB = new JRadioButton("get number"); private JRadioButton changeRB = new JRadioButton("change number"); private JTextArea instruct = new JTextArea(2, 20); private JComboBox nameList = new JComboBox(); private JButton submit = new JButton("Submit"); private PhoneBook myPhoneBook = new PhoneBook();

public void init() { // Define the layout manager for the applet. getContentPane().setLayout(new FlowLayout());

// Define operations panel and button group for radio buttons. JPanel radButPanel = new JPanel(); radButPanel.add(addRB); radButPanel.add(getRB); radButPanel.add(changeRB); getContentPane().add(radButPanel); ButtonGroup operations = new ButtonGroup(); operations.add(addRB); operations.add(getRB); operations.add(changeRB);

// Add instructions text area to applet. instruct.setText("Choose an operation above"); getContentPane().add(instruct);

Copyright © 2003 Pearson Education, Inc. Slide 7-39

PhoneBookGUI method init(), cont’d.

// Define panel for entering name and number. JPanel dataPanel = new JPanel(); JLabel nameLabel = new JLabel("name >> "); dataPanel.add(nameLabel); dataPanel.add(nameText); JLabel numberLabel = new JLabel("number >> "); dataPanel.add(numberLabel); dataPanel.add(numberText); getContentPane().add(dataPanel);

// Define panel for combo box and submit button. JPanel controlPanel = new JPanel(); nameList.addItem("Select a name >>"); // first selection controlPanel.add(nameList); controlPanel.add(submit); getContentPane().add(controlPanel);

// Register event listeners. addRB.addActionListener(this); getRB.addActionListener(this); changeRB.addActionListener(this); submit.addActionListener(this); nameList.addItemListener(this); } // end init

Copyright © 2003 Pearson Education, Inc. Slide 7-40

PhoneBookGUI method actionPerformed() // postcondition: Displays instructions for performing // an operation when a radio button is pressed. // Performs the selected operation when the submit button // is pressed. public void actionPerformed(ActionEvent e) { String name; String number; Friend aFriend; Object but = e.getSource(); if (but == addRB) instruct.setText("Enter name and number and " + "\nPress submit"); else if (but == getRB) instruct.setText("Select name or enter name." + "\nPress submit"); else if (but == changeRB) instruct.setText("Select name or enter name." + "\nEnter new number and press submit"); else if (but == submit && addRB.isSelected()) { // add new friend name = nameText.getText(); number = numberText.getText(); if (name.equals("") || number.equals("")) { instruct.setText("Missing name or number - " + "\nTry again"); return; } aFriend = new Friend(name, number); myPhoneBook.addFriend(aFriend); nameList.addItem(name); // add name to combo box list instruct.setText("Added: " + aFriend + "\nChoose another operation above" ); nameText.setText(""); numberText.setText(""); }

Copyright © 2003 Pearson Education, Inc. Slide 7-41

method actionPerformed(), contd. else if (but == submit && getRB.isSelected()) { // get a number name = nameText.getText(); if (name.equals("")) { instruct.setText("Missing name - " + "\nTry again"); return; } number = myPhoneBook.getNumber(name); instruct.setText("Number is " + number + "\nChoose another operation above"); nameText.setText(""); } else if (but == submit && changeRB.isSelected()) { // change an entry name = nameText.getText(); number = numberText.getText(); if (name.equals("") || number.equals("")) { instruct.setText("Missing name or number - " + "\nTry again"); return; } aFriend = new Friend(name, number); int index = myPhoneBook.findFriend(name); if (index > -1) { myPhoneBook.setFriend(index, aFriend); instruct.setText("Entry changed to: " + aFriend + "\nChoose another operation above" ); } else { instruct.setText(name + " not found - " + "\nTry again"); } nameText.setText(""); numberText.setText(""); }

Copyright © 2003 Pearson Education, Inc. Slide 7-42

actionPerformed(), cont’d, and itemStateChanged()

nameText.requestFocus(); nameList.setSelectedIndex(0); // Reset combo box message } // end actionPerformed()

// postcondition: Stores the name selected from the // combo box list in nameText. public void itemStateChanged(ItemEvent e) { if (e.getSource() == nameList && nameList.getSelectedIndex() != 0) { String name = (String) nameList.getSelectedItem(); nameText.setText(name); } }

Copyright © 2003 Pearson Education, Inc. Slide 7-43

7.7 Listener classes as inner classes

• An alternative to placing a single actionPerformed() method or itemStateChanged() method inside an applet is to use inner listener classes to respond to individual events or to respond to a group of events. • The inner listener classes should be wholly contained within the GUI class. This enables the inner classes to reference private data fields of the GUI.

• If we use an inner listener class RadioButtonListener to listen to action events, we must declare a RadioButtonListener object and register it as the listener for RadioButton events:

RadioButtonListener rBL = new RadioButtonListener();addRB.addActionListener(rBL);getRB.addActionListener(rBL);changeRB.addActionListener(rBL);

Copyright © 2003 Pearson Education, Inc. Slide 7-44

Inner class RadioButtonListener

/* inner class RadioButtonListener for class PhoneBookGUI * Listens for a radio button event. */ private class RadioButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { Object but = e.getSource(); if (but == addRB) instruct.setText("Enter name and number and " + "\nPress submit"); else if (but == getRB) instruct.setText("Select name or enter name." + "\nPress submit"); else if (but == changeRB) instruct.setText( "Select name or enter name." + "\nEnter new number and press submit"); nameText.requestFocus(); } } // end RadioButtonListener

Copyright © 2003 Pearson Education, Inc. Slide 7-45

7.8 Layout managers

• A layout manager is an object that determines the size and placement of objects in a container. • Every container has a default layout manager. The default layout for class Applet (from AWT) is flow layout, the default layout for class JApplet (from Swing) is border layout, and the default layout for class Panel or JPanel is flow layout.• We can change the layout manager for a container by applying its setLayout() method to the container. For a JApplet or JFrame container, apply this method to the container’s content pane.

Copyright © 2003 Pearson Education, Inc. Slide 7-46

Layout manager descriptions

Layout Manager Description

java.awt.BorderLayout Arranges objects in five areas of thecontainer: North, West, Center, East, andSouth.

javax.swing.BoxLayout Arranges objects in a single row orcolumn.

java.awt.FlowLayout Arranges objects in left-to-right orderacross the container, flowing down tothe next row when a row is filled.

java.awt.GridLayout Arranges objects in a two-dimensionalgrid.

Copyright © 2003 Pearson Education, Inc. Slide 7-47

Flow layout

• Flow layout is the simplest form of layout and is the default for the JPanel and Applet classes. Flow layout puts as many components on a row as will fit. When a row is filled, the next row of components is assembled.

• Components can be centered, left-justified, or right-justified. The default is centered, but you can specify a different alignment when you create the flow layout object. Use the predefined constant FlowLayout.LEFT to specify left-justified alignment; use the predefined constant FlowLayout.RIGHT to specify right-justified alignment:setLayout(new FlowLayout(FlowLayout.RIGHT))

Copyright © 2003 Pearson Education, Inc. Slide 7-48

Border layout

Border Layout sets up five areas in which components can be placed and is the default for class JApplet.

You can only put one component in each area, so if you want to put two or more components in an area, you need to first place them in a panel and then place the panel in that area. If an area contains no components, the Center area will expand to fill that space. To specify border layout:

setLayout(new BorderLayout( ))

North

West Center East

South

Copyright © 2003 Pearson Education, Inc. Slide 7-49

PhoneBook GUI with border layout

getContentPane().setLayout(new BorderLayout( ))

getContentPane().add(radButPanel, BorderLayout.NORTH);getContentPane().add(instruct, BorderLayout.WEST);getContentPane().add(dataPanel, BorderLayout.CENTER);getContentPane().add(controlPanel, BorderLayout.SOUTH);

North

West Center

South

Copyright © 2003 Pearson Education, Inc. Slide 7-50

Box layoutBox layout places components in either a single row or a single column. The statements below use box layout to align the radio buttons in a single column in panel radButPanel.

JPanel radButPanel = new JPanel();radButPanel.setLayout(new BoxLayout(radButPanel, BoxLayout.Y_AXIS));radButPanel.add(addRB);radButPanel.add(getRB);radButPanel.add(changeRB);getContentPane().add(radButPanel, BorderLayout.NORTH);

columnlayout

columnlayout

North

Copyright © 2003 Pearson Education, Inc. Slide 7-51

Grid layout

Grid layout positions components such as buttons in a two-dimensional grid. The buttons for a calculator are in a grid pattern of four rows and three columns. Buttons for the digit characters 1 through 9 are in the first three rows. Buttons with characters C (for clear), the digit 0, and the decimal point . character are in the fourth row.

Copyright © 2003 Pearson Education, Inc. Slide 7-52

Class CalculatorButtons

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

public class CalculatorButtons extends JApplet implements ActionListener {

private JButton[] digitButtons; private JTextField result = new JTextField(10);

// postcondition: Displays a 4 X 3 grid of buttons in the applet. // The buttons in the first row have labels 1, 2, 3. public void init() { String[] buttonLabels = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "C", "0", "."};

// Create an array of buttons. digitButtons = new JButton[buttonLabels.length];

// Create a 4 x 3 grid for placement of buttons. JPanel buttonGrid = new JPanel(); buttonGrid.setLayout(new GridLayout(4, 3));

// Create a button with each button label, add it to buttonGrid, // and register the applet as a listener. for (int nextBut = 0; nextBut < digitButtons.length; nextBut++) { digitButtons[nextBut] = new JButton(buttonLabels[nextBut]); digitButtons[nextBut].addActionListener(this); buttonGrid.add(digitButtons[nextBut]); }

Copyright © 2003 Pearson Education, Inc. Slide 7-53

Class CalculatorButtons, cont’d.

JLabel instruct = new JLabel("Press a button"); getContentPane().add(instruct, BorderLayout.NORTH); getContentPane().add(buttonGrid, BorderLayout.CENTER); getContentPane().add(result, BorderLayout.SOUTH); }

// postcondition: Displays the label of the button pressed. public void actionPerformed(ActionEvent aE) { Object whichButton = aE.getSource(); for (int nextBut = 0; nextBut < digitButtons.length; nextBut++) { if (whichButton == digitButtons[nextBut]) result.setText("You pressed " + digitButtons[nextBut].getText()); } }}