Presentation is loading. Please wait.

Presentation is loading. Please wait.

 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1.

Similar presentations


Presentation on theme: " 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1."— Presentation transcript:

1  1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1

2  1992-2007 Pearson Education, Inc. All rights reserved. 2 OBJECTIVES In this chapter you will learn:  The design principles of graphical user interfaces (GUIs).  To build GUIs and handle events generated by user interactions with GUIs.  To understand the packages containing GUI components, event-handling classes and interfaces.  To create and manipulate buttons, labels, lists, text fields and panels.  To handle mouse events and keyboard events.  To use layout managers to arrange GUI components

3  1992-2007 Pearson Education, Inc. All rights reserved. 3 11.1 Introduction 11.2 Simple GUI-Based Input/Output with JOptionPane 11.3 Overview of Swing Components 11.4 Displaying Text and Images in a Window 11.5 Text Fields and an Introduction to Event Handling with Nested Classes 11.6 Common GUI Event Types and Listener Interfaces 11.7 How Event Handling Works 11.8 JButton 11.9 Buttons That Maintain State 11.9.1 JCheckBox 11.9.2 JRadioButton 11.10 JComboBox and Using an Anonymous Inner Class for Event Handling

4  1992-2007 Pearson Education, Inc. All rights reserved. 4 11.11 JList 11.12 Multiple-Selection Lists 11.13 Mouse Event Handling 11.14 Adapter Classes 11.15 JPanel Sublcass for Drawing with the Mouse 11.16 Key-Event Handling 11.17 Layout Managers 11.17.1 FlowLayout 11.17.2 BorderLayout 11.17.3 GridLayout 11.18 Using Panels to Manage More Complex Layouts 11.19 JTextArea 11.20 Wrap-Up

5  1992-2007 Pearson Education, Inc. All rights reserved. 5 11.1 Introduction Graphical user interface (GUI) – Presents a user-friendly mechanism for interacting with an application – Often contains title bar, menu bar containing menus, buttons and combo boxes – Built from GUI components

6  1992-2007 Pearson Education, Inc. All rights reserved. 6 Fig. 11.1 | Internet Explorer window with GUI components. buttonmenustitle barmenu barcombo box scroll bars

7  1992-2007 Pearson Education, Inc. All rights reserved. 7 11.2 Simple GUI-Based Input/Output with JOptionPane Dialog boxes – Used by applications to interact with the user – Provided by Java’s JOptionPane class Contains input dialogs and message dialogs invoking static JOptionPane methods

8  1992-2007 Pearson Education, Inc. All rights reserved. 8 Example: JOptionPane import javax.swing.JOptionPane; // program uses JOptionPane public class Addition { public static void main( String args[]) { // obtain user input from JOptionPane input dialogs String firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); String secondNumber = JOptionPane.showInputDialog( "Enter second integer" ); // convert String inputs to int values for use in a calculation int number1 = Integer.parseInt( firstNumber ); int number2 = Integer.parseInt( secondNumber ); int sum = number1 + number2; // add numbers

9  1992-2007 Pearson Education, Inc. All rights reserved. 9 Example (cont.) // display result in a JOptionPane message dialog JOptionPane.showMessageDialog(null,"The sum is " + sum,"Sum of Two Integers", JOptionPane.PLAIN_MESSAGE ); } // end method main } // end class Addition

10  1992-2007 Pearson Education, Inc. All rights reserved. 10 Outline Addition.java (1 of 2)

11  1992-2007 Pearson Education, Inc. All rights reserved. 11 Outline Addition.java (2 of 2) Input dialog displayed by lines 10–11 Input dialog displayed by lines 12 – 13 Message dialog displayed by lines 22 – 23 Text field in which the user types a value Prompt to the user When the user clicks OK, showInputDialog returns to the program the 100 typed by the user as a String. The program must convert the String to an int title bar When the user clicks OK, the message dialog is dismissed (removed from the screen)

12  1992-2007 Pearson Education, Inc. All rights reserved. 12 11.2 Simple GUI-Based Input/Output with JOptionPane Input dialogs – return String Converting String to int values – Integer class static parseInt method – converts its String argument to an int value Message Dialogs – JOptionPane’s static method showMessageDialog 1th argumenet – possition – null: center of screen 2th argument - message to be display 3th argument – String on the Title bar of the dialog box 4th argument – constants:icon types

13  1992-2007 Pearson Education, Inc. All rights reserved. 13 Fig. 11.3 | JOptionPane static constants for message dialogs.

14  1992-2007 Pearson Education, Inc. All rights reserved. 14 11.3 Overview of Swing Components Swing GUI components – Declared in package javax.swing – Most are pure Java components – Part of the Java Foundation Classes (JFC)

15  1992-2007 Pearson Education, Inc. All rights reserved. 15 Fig. 11.4 | Some basic GUI components.

16  1992-2007 Pearson Education, Inc. All rights reserved. 16 Swing vs. AWT Abstract Window Toolkit (AWT) – Precursor to Swing – Declared in package java.awt – Does not provide consistent, cross-platform look-and-feel

17  1992-2007 Pearson Education, Inc. All rights reserved. 17 Portability Tip 11.1 Swing components are implemented in Java, so they are more portable and flexible than the original Java GUI components from package java.awt, which were based on the GUI components of the underlying platform. For this reason, Swing GUI components are generally preferred.

18  1992-2007 Pearson Education, Inc. All rights reserved. 18 Lightweight vs. Heavyweight GUI Components Lightweight components – Not tied directly to GUI components supported by underlying platform Heavyweight components – Tied directly to the local platform – AWT components – Some Swing components

19  1992-2007 Pearson Education, Inc. All rights reserved. 19 Look-and-Feel Observation 11.4 The look and feel of a GUI defined with heavyweight GUI components from package java.awt may vary across platforms. Because heavyweight components are tied to the local- platform GUI, the look and feel varies from platform to platform.

20  1992-2007 Pearson Education, Inc. All rights reserved. 20 Superclasses of Swing’s Lightweight GUI Components Class Component (package java.awt ) – Subclass of Object – Declares many behaviors and attributes common to GUI components Class Container (package java.awt ) – Subclass of Component – Organizes Component s Class JComponent (package javax.swing ) – Subclass of Container – Superclass of all lightweight Swing components

21  1992-2007 Pearson Education, Inc. All rights reserved. 21 Software Engineering Observation 11.1 Study the attributes and behaviors of the classes in the class hierarchy of Fig. 11.5. These classes declare the features that are common to most Swing components.

22  1992-2007 Pearson Education, Inc. All rights reserved. 22 Fig. 11.5 | Common superclasses of many of the Swing components.

23  1992-2007 Pearson Education, Inc. All rights reserved. 23 Superclasses of Swing’s Lightweight GUI Components Common lightweight component features – Pluggable look-and-feel to customize the appearance of components – Shortcut keys (called mnemonics) – Common event-handling capabilities – Brief description of component’s purpose (called tool tips) – Support for localization

24  1992-2007 Pearson Education, Inc. All rights reserved. 24 11.4 Displaying Text and Images in a Window Class JFrame – Most windows are an instance or subclass of this class – Provides title bar – Provides buttons to minimize, maximize and close the application

25  1992-2007 Pearson Education, Inc. All rights reserved. 25 import javax.swing.*; public class FrameTest { public static void main(String args[]) { JFrame firstFrame = new JFrame("First Frame"); firstFrame.setDefaultCloseOperation(JFrame.EXIT_O N_CLOSE); firstFrame.setSize(200, 300); firstFrame.setVisible(true); } // end main } // end class FrameTest

26  1992-2007 Pearson Education, Inc. All rights reserved. 26 Output an empty JFrame

27  1992-2007 Pearson Education, Inc. All rights reserved. 27 JFrame firstFrame = new JFrame("First Frame"); firstFrame : reference of type JFrame – in javax.swing package create JFrame object by setting its title JFrame indirect subclass of java.awt.Window – attributes and behavior of a window: Title bar at the top buttoms for closing, minimizing...

28  1992-2007 Pearson Education, Inc. All rights reserved. 28 Creating and Displaying a LabelFrame Window Other JFrame methods – setDefaultCloseOperation Dictates how the application reacts when the user clicks the close button – setSize Specifies the width and height of the window – setVisible Determines whether the window is displayed ( true ) or not ( false )

29  1992-2007 Pearson Education, Inc. All rights reserved. 29 Labeling GUI Components Label – Text instructions or information stating the purpose of each component – Created with class JLabel

30  1992-2007 Pearson Education, Inc. All rights reserved. 30 General Framework for GUI Applications A subclass of JFrame – illustrate new GUI concepts An application class – main creates and displays the applicatins window

31  1992-2007 Pearson Education, Inc. All rights reserved. 31 Look-and-Feel Observation 11.5 Text in a JLabel normally uses sentence-style capitalization.

32  1992-2007 Pearson Education, Inc. All rights reserved. 32 Adding a label to the Frame class Label1 import javax.swing.*; import java.awt.*; public class Label0 { public static void main(String[] args){ LabelFrame firstLabel = new LabelFrame("Frame with Label"); firstLabel.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE); firstLabel.setSize(200, 300); firstLabel.setVisible(true); } // end main } // end class Label1

33  1992-2007 Pearson Education, Inc. All rights reserved. 33 class LabelFrame extends JFrame { // creates a JLabel reference private JLabel label1; public LabelFrame(String title) { super(title); // send the title to JFrame’s consturctor // set labout setLayout(new FlowLayout()); // create a new JLabel refered by label1 label1 = new JLabel("I am a label"); add(label1); // add to the frame } // end constructor } // end classLabelFrame

34  1992-2007 Pearson Education, Inc. All rights reserved. 34 Class Label0 – test or application class LabelFrame firstLabel = new LabelFrame("Frame with Label"); LabelFrame extends from JFrame firstLabel: is a reference to a LabelFrame type object Create the object with its title use methods of JFrame to set – close operation – size – visiblilility of the firstLabel

35  1992-2007 Pearson Education, Inc. All rights reserved. 35 Class LabelFrame - extends from JFrame – hold the components – label1 – set the layout – create the labels label1 – add to the JFrame

36  1992-2007 Pearson Education, Inc. All rights reserved. 36 Another approach – not prefered Create a JFrame object send title to its constrcutor set the properties create a JLabel reference set layout on JFrame create the object label1 add label1 to jlabelFrame

37  1992-2007 Pearson Education, Inc. All rights reserved. 37 import javax.swing.*; import java.awt.*; public class Label0 { public static void main(String[] args) { JFrame firstLabel = new JFrame("Frame with Label"); firstLabel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); firstLabel.setSize(200, 300); firstLabel.setVisible(true); JLabel label1; // a JLabel type varible firstLabel. setLayout(new FlowLayout()); // create a new JLabel refered by label1 label1 = new JLabel("I am a label"); firstLabel.add(label1); // add to the frame } // end main } // end class Label1

38  1992-2007 Pearson Education, Inc. All rights reserved. 38 Adding a labels to the Frame class Label1 import javax.swing.*; import java.awt.*; public class Label1 { public static void main(String[] args) { LabelFrame firstLabel = new LabelFrame("Frame with Label"); firstLabel.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); firstLabel.setSize(200, 300); firstLabel.setVisible(true); } // end main } // end class Label1

39  1992-2007 Pearson Education, Inc. All rights reserved. 39 Explanations LabelFrame firstLabel = new LabelFrame("Frame with Label"); LabelFrame extends from JFrame firstLabel: is a reference to a LabelFrame type object Create the object with its title use methods of JFrame to set – close operation – size – visiblilility of the firstLabel

40  1992-2007 Pearson Education, Inc. All rights reserved. 40 class Label1Frame extends from JFrame hold the components – 3 JLabel s set the layout create the labels label1 and label2 – seting a tooltip for label2 – toolTipSet method add to the JFrame

41  1992-2007 Pearson Education, Inc. All rights reserved. 41 class Label1Freme class LabelFrame extends JFrame { // creates three JLabel references private JLabel label1; private JLabel label2; private JLabel label3; public LabelFrame(String title) { super(title); // send the title to JFrame’s consturctor // set labout setLayout(new FlowLayout());

42  1992-2007 Pearson Education, Inc. All rights reserved. 42 // create a new JLabel refered by label1 label1 = new JLabel("I am a label"); add(label1); // add to the frame // create a new JLabel refered by label2 label2 = new JLabel("second label"); label2.setToolTipText("tooltip of scond label"); // set a tooltip to label2 invoking setToolTip method add(label2); // add to the frame

43  1992-2007 Pearson Education, Inc. All rights reserved. 43 // create a new JLabel refered by label3 label3 = new JLabel(); label3.setText("label 3"); label3.setToolTipText("tool tip text 3"); label3.setHorizontalTextPosition(SwingConstan ts.CENTER); label3.setVerticalTextPosition(SwingConstants.BOTTOM); add(label3);; } // end constructor } // end class LabelFrame

44  1992-2007 Pearson Education, Inc. All rights reserved. 44 Specifying the Layout Laying out containers – Determines where components are placed in the container Window creatred with JFrame – Done in Java with layout managers One of which is class FlowLayout – Set with the setLayout method İnherited indirectly form class Container setLayout(new FlowLayout()); – A FlowLayout object is created without a reference and send to setLayout method as an argument – The parameter lacal variable is the refernce – LayoutManager interface

45  1992-2007 Pearson Education, Inc. All rights reserved. 45 output of program

46  1992-2007 Pearson Education, Inc. All rights reserved. 46 Outline LabelFrame.java (1 of 2)

47  1992-2007 Pearson Education, Inc. All rights reserved. 47 Outline LabelFrame.java (1 of 2)

48  1992-2007 Pearson Education, Inc. All rights reserved. 48 Outline LabelFrame.java (2 of 2)

49  1992-2007 Pearson Education, Inc. All rights reserved. 49 Outline LabelTest.java

50  1992-2007 Pearson Education, Inc. All rights reserved. 50 Outline LabelTest.java

51  1992-2007 Pearson Education, Inc. All rights reserved. 51 Creating and Attaching label1 Method setToolTipText of class JComponent – Specifies the tool tip Method add of class Container – Adds a component to a container

52  1992-2007 Pearson Education, Inc. All rights reserved. 52 Common Programming Error 11.1 If you do not explicitly add a GUI component to a container, the GUI component will not be displayed when the container appears on the screen.

53  1992-2007 Pearson Education, Inc. All rights reserved. 53 Look-and-Feel Observation 11.6 Use tool tips to add descriptive text to your GUI components. This text helps the user determine the GUI component’s purpose in the user interface.

54  1992-2007 Pearson Education, Inc. All rights reserved. 54 Creating and Attaching label2 Interface Icon – Can be added to a JLabel with the setIcon method – Implemented by class ImageIcon Interface SwingConstants – Declares a set of common integer constants such as those used to set the alignment of components – Can be used with methods setHorizontalAlignment and setVerticalAlignment

55  1992-2007 Pearson Education, Inc. All rights reserved. 55 Creating and Attaching label3 Other JLabel methods – getText and setText For setting and retrieving the text of a label – getIcon and setIcon For setting and retrieving the icon displayed in the label – getHorizontalTextPosition and setHorizontalTextPosition For setting and retrieving the horizontal position of the text displayed in the label

56  1992-2007 Pearson Education, Inc. All rights reserved. 56 Fig. 11.8 | Some basic GUI components.

57  1992-2007 Pearson Education, Inc. All rights reserved. 57 11.5 Text Fields and an Introduction to Event Handling with Nested Classes GUIs are event-driven – A user interaction creates an event Common events are: – clicking a button – typing in a text field – selecting an item from a menu – closing and window – moving the mouse – The event causes a call to a method called an event handler

58  1992-2007 Pearson Education, Inc. All rights reserved. 58 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Button0 { public static void main(String[] args) { ButtonFrame jButtonFrame = new ButtonFrame("Title"); jButtonFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jButtonFrame.setLocationRelativeTo(null); jButtonFrame.setSize(200, 400); jButtonFrame.setVisible(true); }

59  1992-2007 Pearson Education, Inc. All rights reserved. 59 class ButtonFrame extends JFrame { private JButton button; public ButtonFrame(String title) { super(title); setLayout(new FlowLayout()); button = new JButton("I am a Button"); add(button); ButtonHandler handler = new ButtonHandler(); button.addActionListener(handler); } // end constructor

60  1992-2007 Pearson Education, Inc. All rights reserved. 60 private class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog( null,"You clicked me"); } // end actionPerformed } // end inner class } // end class ButtonFrame

61  1992-2007 Pearson Education, Inc. All rights reserved. 61 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Button1 { public static void main(String[] args) { JFrame jButton = new JFrame("Title"); jButton.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jButton.setLocationRelativeTo(null); jButton.setSize(200, 400); jButton.setVisible(true); jButton.setLayout(new FlowLayout());

62  1992-2007 Pearson Education, Inc. All rights reserved. 62 JButton button; button = new JButton("I am a Button"); jButton.add(button); ButtonHandler handler = new ButtonHandler(); button.addActionListener(handler); } // end main } // end class Button1

63  1992-2007 Pearson Education, Inc. All rights reserved. 63 class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog( null,"You clicked me"); } // end of actionPerformed } // end of class

64  1992-2007 Pearson Education, Inc. All rights reserved. 64 output of the program

65  1992-2007 Pearson Education, Inc. All rights reserved. 65 11.5 Text Fields and an Introduction to Event Handling with Nested Classes Class JTextComponent – Superclass of JTextField Superclass of JPasswordField – Adds echo character to hide text input in component – Allows user to enter text in the component when component has the application’s focus

66  1992-2007 Pearson Education, Inc. All rights reserved. 66 11.5 Text Fields and an Introduction to Event Handling with Nested Classes import javax.swing.*; import java.awt.*; public class Text0 { public static void main(String[] args) { JText0 jTextFrame = new JText0("TextField"); jTextFrame.setDefaultCloseOperation(JFrame.EXIT_O N_CLOSE); jTextFrame.setSize(200, 400); jTextFrame.setVisible(true); } end main } end class Text0

67  1992-2007 Pearson Education, Inc. All rights reserved. 67 Program continued class JText0 extends JFrame { private JTextField textField1; public JText0(String title) { super(title); setLayout(new FlowLayout()); textField1 = new JTextField(10); add(textField1); TextHandler handler = new TextHandler(); textField1.addActionListener(handler); } // end constructor JText0 // the class has not ended

68  1992-2007 Pearson Education, Inc. All rights reserved. 68 Program continued private class TextHandler implements ActionListener { public void actionPerformed(ActionEvent e) { String string = String.format( “text field:%s”,e.getActionCommand()); JOptionPane.showMessageDialog(null,string); } // end method actionPerformed } // end innter class TextHandler } // end class JText0

69  1992-2007 Pearson Education, Inc. All rights reserved. 69 Another version using getText method private class TextHandler implements ActionListener { public void actionPerformed(ActionEvent e) { // useing the getText method String string = String.format( “text field:%s”,textField1.getText()); JOptionPane.showMessageDialog(null,string); } // end method actionPerformed } // end innter class TextHandler } // end class JText0

70  1992-2007 Pearson Education, Inc. All rights reserved. 70 The output:

71  1992-2007 Pearson Education, Inc. All rights reserved. 71 11.5 Text Fields and an Introduction to Event Handling with Nested Classes import javax.swing.*; import java.awt.*; public class Text0 { public static void main(String[] args) { JText0 jTextFrame = new JText0("TextField"); jTextFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CL OSE); jTextFrame.setSize(200, 400); jTextFrame.setVisible(true); }

72  1992-2007 Pearson Education, Inc. All rights reserved. 72 class JText0 extends JFrame { private JTextField textField1; private JTextField textField2; public JText0(String title) { super(title); setLayout(new FlowLayout()); textField1 = new JTextField(10); textField2 = new JTextField("Enter text"); add(textField1); add(textField2); TextHandler handler = new TextHandler(); textField1.addActionListener(handler); textField2.addActionListener(handler); } // end constructor JText0

73  1992-2007 Pearson Education, Inc. All rights reserved. 73 Another version private class TextHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if(e.getSource()==textField1) String string = String.format(“text field:%s”, textField1.getText ()); else String string = String.format(“text field:%s”, textField2.getText ()); JOptionPane.showMessageDialog(null,string); } // end method actionPerformed } // end innter class TextHandler } // end class JText0

74  1992-2007 Pearson Education, Inc. All rights reserved. 74

75  1992-2007 Pearson Education, Inc. All rights reserved. 75 Text and Pasword Fields Book’s example import java.awt.*; import javax.swing.*; public class TextFieldTest { public static void main( String args[] ){ TextFieldFrame textFieldFrame = new TextFieldFrame(); textFieldFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); textFieldFrame.setSize( 325, 100 ); textFieldFrame.setVisible( true ); } // end main } // end class TextFieldTest

76  1992-2007 Pearson Education, Inc. All rights reserved. 76 Example (cont.) class TextFieldFrame extends JFrame { // text field with set size private JTextField textField1; // text field constructed with text private JTextField textField2; // text field with text and size private JTextField textField3; // password field with text private JPasswordField passwordField;

77  1992-2007 Pearson Education, Inc. All rights reserved. 77 Example (cont.) // TextFieldFrame constructor adds JTextFields to JFrame public TextFieldFrame() { super( "Testing JTextField and JPasswordField"); // set frame layout setLayout( new FlowLayout() ); // construct textfield with 10 columns textField1 = new JTextField( 10 ); // add textField1 to JFrame add( textField1 ); // construct textfield with default text textField2 = new JTextField( "Enter text here" ); // add textField2 to JFrame add( textField2 );

78  1992-2007 Pearson Education, Inc. All rights reserved. 78 Example (cont.) // construct textfield with default text and 21 columns textField3 = new JTextField( "Uneditable text field", 21); // disable editing textField3.setEditable( false ); // add textField3 to JFrame add( textField3 ); // construct passwordfield with default text passwordField = new JPasswordField( "Hidden text"); // add passwordField to JFrame add( passwordField );

79  1992-2007 Pearson Education, Inc. All rights reserved. 79 Example (cont.) // register event handlers TextFieldHandler handler = new TextFieldHandler(); textField1.addActionListener( handler ); textField2.addActionListener( handler ); textField3.addActionListener( handler ); passwordField.addActionListener( handler ); } // end TextFieldFrame constructor

80  1992-2007 Pearson Education, Inc. All rights reserved. 80 Example (cont.) // private inner class for event handling private class TextFieldHandler implements ActionListener { // process text field events public void actionPerformed( ActionEvent event ) { String string = ""; // declare string to display // user pressed Enter in JTextField textField1 if ( event.getSource() == textField1 ) string = String.format( "textField1: %s", event.getActionCommand() ); // user pressed Enter in JTextField textField2 else if ( event.getSource() == textField2 ) string = String.format( "textField2: %s", event.getActionCommand() );

81  1992-2007 Pearson Education, Inc. All rights reserved. 81 Example (cont.) // user pressed Enter in JTextField passwordField else if ( event.getSource() == passwordField ) string = String.format( "passwordField: %s", new String( passwordField.getPassword() ) ); // display JTextField content JOptionPane.showMessageDialog(null,string); } // end method actionPerformed } // end private inner class TextFieldHandler } // end class TextFieldFrame

82  1992-2007 Pearson Education, Inc. All rights reserved. 82 Outline TextFieldTest.java (1 of 2)

83  1992-2007 Pearson Education, Inc. All rights reserved. 83 Outline TextFieldTest.java (2 of 2)

84  1992-2007 Pearson Education, Inc. All rights reserved. 84 Steps Required to Set Up Event Handling for a GUI Component Several coding steps are required for an application to respond to events – Create a class for the event handler – Implement an appropriate event-listener interface – Register the event handler

85  1992-2007 Pearson Education, Inc. All rights reserved. 85 Using a Nested Class to Implement an Event Handler Top-level classes – Not declared within another class Nested classes – Declared within another class – Non- static nested classes are called inner classes Frequently used for event handling

86  1992-2007 Pearson Education, Inc. All rights reserved. 86 Software Engineering Observation 11.2 An inner class is allowed to directly access its top-level class’s variables and methods, even if they are private.

87  1992-2007 Pearson Education, Inc. All rights reserved. 87 Using a Nested Class to Implement an Event Handler JTextField s and JPasswordField s – Pressing enter within either of these fields causes an ActionEvent Processed by objects that implement the ActionListener interface

88  1992-2007 Pearson Education, Inc. All rights reserved. 88 Registering the Event Handler for Each Text Field Registering an event handler – Call method addActionListener to register an ActionListener object – ActionListener listens for events on the object

89  1992-2007 Pearson Education, Inc. All rights reserved. 89 Software Engineering Observation 11.3 The event listener for an event must implement the appropriate event-listener interface.

90  1992-2007 Pearson Education, Inc. All rights reserved. 90 Common Programming Error 11.2 Forgetting to register an event-handler object for a particular GUI component’s event type causes events of that type to be ignored.

91  1992-2007 Pearson Education, Inc. All rights reserved. 91 Details of Class TextFieldHandler ’s actionPerformed Method Event source – Component from which event originates – Can be determined using method getSource – Text from a JTextField can be acquired using getActionCommand – Text from a JPasswordField can be acquired using getPassword

92  1992-2007 Pearson Education, Inc. All rights reserved. 92 11.6 Common GUI Event Types and Listener Interfaces when the user presses enter in a textFieald – information is stored in ActionEvent object many different events occur when the user interracts with the GUI – information is stored in different objects whose classes inherit from AWTEvent

93  1992-2007 Pearson Education, Inc. All rights reserved. 93 11.6 Common GUI Event Types and Listener Interfaces Event types – All are subclasses of AWTEvent – Some declared in package java.awt.event – Those specific to Swing components declared in javax.swing.event

94  1992-2007 Pearson Education, Inc. All rights reserved. 94 11.6 Common GUI Event Types and Listener Interfaces event source event object event listener

95  1992-2007 Pearson Education, Inc. All rights reserved. 95 11.6 Common GUI Event Types and Listener Interfaces Delegation event model – Event source is the component with which user interacts – Event object is created and contains information about the event that happened any event specific information e.g.: text entered in a text box – Event listener is notified when an event happens one of its methods executes when an event occurs get information about the event from the event object what to do when an event occurs coded in event listener that get infromation from event object

96  1992-2007 Pearson Education, Inc. All rights reserved. 96 Fig. 11.11 | Some event classes of package java.awt.event.

97  1992-2007 Pearson Education, Inc. All rights reserved. 97 Fig. 11.12 | Some common event-listener interfaces of package java.awt.event.

98  1992-2007 Pearson Education, Inc. All rights reserved. 98 Event listeners a corresponding listener for each event object interface so all of its method must be implemented in concrete classes sooner or later – mostly in package java.awt.event – soma additional in javax.swing.event each contains one or more methods – e.g.: when the user press Enter in a text field – the listeners actionPerformed method is called

99  1992-2007 Pearson Education, Inc. All rights reserved. 99 11.7 How Event Handling Works Remaining questions – How did the event handler get registered? – How does the GUI component know to call actionPerformed rather than some other event- handling method?

100  1992-2007 Pearson Education, Inc. All rights reserved. 100 Registering Events Every JComponent has instance variable listenerList – Object of type EventListenerList – Maintains references to all its registered listeners

101  1992-2007 Pearson Education, Inc. All rights reserved. 101 Fig. 11.13 | Event registration for JTextField textField1.

102  1992-2007 Pearson Education, Inc. All rights reserved. 102 Event-Handler Invocation Events are dispatched to only the event listeners that match the event type – Events have a unique event ID specifying the event type ActionEvents are handled by Actionistener s and MouseEvent s are handled by MouseListener s and MouseMotionsListener s KeyEvent s are handled by KeyListener s Dispatching: – the process by which GUI component calls an event handling method on each of its registered listeners

103  1992-2007 Pearson Education, Inc. All rights reserved. 103 Event-Handler Invocation For an ActionEvent the event is dispatched to every registered listeners actionPerformed method (the only method) For a MouseEvent the event is dispatched to every registered MouseListner or MouseMotion listener depending on the event occur – Which method to call is determined by the event ID Just register an event handler for the particular event type – Appropriate method of the event handler is called when the envet occurs

104  1992-2007 Pearson Education, Inc. All rights reserved. 104 11.8 JButton Button – Component user clicks to trigger a specific action – Can be command button, check box, toggle button or radio button – Button types are subclasses of class AbstractButton

105  1992-2007 Pearson Education, Inc. All rights reserved. 105 Look-and-Feel Observation 11.7 Buttons typically use book-title capitalization.

106  1992-2007 Pearson Education, Inc. All rights reserved. 106 11.8 JButton Command button – Generates an ActionEvent when it is clicked – Created with class JButton – Text on the face of the button is called button label

107  1992-2007 Pearson Education, Inc. All rights reserved. 107 Look-and-Feel Observation 11.8 Having more than one JButton with the same label makes the JButton s ambiguous to the user. Provide a unique label for each button.

108  1992-2007 Pearson Education, Inc. All rights reserved. 108 Fig. 11.14 | Swing button hierarchy.

109  1992-2007 Pearson Education, Inc. All rights reserved. 109 Outline ButtonFrame.java (1 of 2)

110  1992-2007 Pearson Education, Inc. All rights reserved. 110 Outline ButtonFrame.java (1 of 2)

111  1992-2007 Pearson Education, Inc. All rights reserved. 111 Outline ButtonTest.java (1 of 2)

112  1992-2007 Pearson Education, Inc. All rights reserved. 112 Outline ButtonTest.java (1 of 2)

113  1992-2007 Pearson Education, Inc. All rights reserved. 113 Outline ButtonTest.java (2 of 2)

114  1992-2007 Pearson Education, Inc. All rights reserved. 114 11.8 JButton JButton s can have a rollover icon – Appears when mouse is positioned over a button – Added to a JButton with method setRolloverIcon

115  1992-2007 Pearson Education, Inc. All rights reserved. 115 Look-and-Feel Observation 11.9 Because class AbstractButton supports displaying text and images on a button, all subclasses of AbstractButton also support displaying text and images.

116  1992-2007 Pearson Education, Inc. All rights reserved. 116 Look-and-Feel Observation 11.10 Using rollover icons for JButton s provides users with visual feedback indicating that when they click the mouse while the cursor is positioned over the button, an action will occur.

117  1992-2007 Pearson Education, Inc. All rights reserved. 117 Software Engineering Observation 11.4 When used in an inner class, keyword this refers to the current inner-class object being manipulated. An inner- class method can use its outer-class object’s this by preceding this with the outer-class name and a dot, as in ButtonFrame.this. JOptionPane.showMessageDialog( ButtonFrame.this, String.format( "You pressed: %s", event.getActionCommand() ) );

118  1992-2007 Pearson Education, Inc. All rights reserved. 118 11.9 Buttons That Maintain State State buttons – Swing contains three types of state buttons – JToggleButton, JCheckBox and JRadioButton – JCheckBox and JRadioButton are subclasses of JToggleButton

119  1992-2007 Pearson Education, Inc. All rights reserved. 119 11.9.1 JCheckBox JCheckBox – Contains a check box label that appears to right of check box by default – Generates an ItemEvent when it is clicked ItemEvent s are handled by an ItemListener Passed to method itemStateChanged – Method isSelected returns whether check box is selected ( true ) or not ( false )

120  1992-2007 Pearson Education, Inc. All rights reserved. 120 Test class import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CheckBox0 { public static void main(String[] args) { CheckBoxFrame0 checkBoxFrame0 = new CheckBoxFrame0(); checkBoxFrame0.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); checkBoxFrame0.setSize(400, 400); checkBoxFrame0.setVisible(true); } // end mehod main } endd class CheckBox0

121  1992-2007 Pearson Education, Inc. All rights reserved. 121 class CheckBoxFrame0 extends JFrame { private JLabel priceLabel; private JCheckBox cheeseCheckBox; private JCheckBox salamiCheckBox; private int pricePlane = 10; private int priceCheese = 5; private int priceSalami = 7; private int totalPrice = pricePlane; private String priceString = "price: ";

122  1992-2007 Pearson Education, Inc. All rights reserved. 122 public CheckBoxFrame0() { setLayout(new FlowLayout()); // creating and adding textField priceLabel = new JLabel(priceString+totalPrice); add(priceLabel); // creating and adding checkBox objects cheeseCheckBox = new JCheckBox("Cheese"); salamiCheckBox = new JCheckBox("Salami"); add(cheeseCheckBox); add(salamiCheckBox); // registering events to the checkBoxes CheckBoxHandler handler = new CheckBoxHandler(); cheeseCheckBox.addItemListener(handler); salamiCheckBox.addItemListener(handler); } // end constructor

123  1992-2007 Pearson Education, Inc. All rights reserved. 123 class ChackBoxHandler private class CheckBoxHandler implements ItemListener { public void itemStateChanged(ItemEvent event) { if(event.getSource()==cheeseCheckBox) totalPrice += cheeseCheckBox.isSelected() ? priceCheese :-priceCheese ; if(event.getSource()==salamiCheckBox) totalPrice += salamiCheckBox.isSelected() ? priceSalami :- priceSalami ; priceLabel.setText(priceString+totalPrice); } // end ItemSteteChanged method } // end CheckBoxHandler inner class } // end CheckBoxFrame0 class

124  1992-2007 Pearson Education, Inc. All rights reserved. 124 Another version of the CheckBoxHandler private class CheckBoxHandler implements ItemListener { public void itemStateChanged(ItemEvent event) { if(cheeseCheckBox.isSelected() && salamiCheckBox.isSelected()) totalPrice = priceCheese+priceSalami+pricePlain; else if(cheeseCheckBox.isSelected()) totalPrice = priceCheese+pricePlain; else if(salamiCheckBox.isSelected()) totalPrice = priceSalami+pricePlain; else totalPrice = pricePlain; priceLabel.setText(priceString+totalPrice); } // end ItemSteteChanged method } // end CheckBoxHandler inner class } // end CheckBoxFrame0 class

125  1992-2007 Pearson Education, Inc. All rights reserved. 125

126  1992-2007 Pearson Education, Inc. All rights reserved. 126 Outline CheckBoxFrame.java (1 of 3)

127  1992-2007 Pearson Education, Inc. All rights reserved. 127 Outline CheckBoxFrame.java (2 of 3)

128  1992-2007 Pearson Education, Inc. All rights reserved. 128 Outline CheckBoxFrame.java (3 of 3)

129  1992-2007 Pearson Education, Inc. All rights reserved. 129 Outline CheckBoxTest.java

130  1992-2007 Pearson Education, Inc. All rights reserved. 130 Outline CheckBoxTest.java

131  1992-2007 Pearson Education, Inc. All rights reserved. 131 Outline CheckBoxFrame.java (2 of 3)

132  1992-2007 Pearson Education, Inc. All rights reserved. 132 11.9.2 JRadioButton JRadioButton – Has two states – selected and unselected – Normally appear in a group in which only one radio button can be selected at once Group maintained by a ButtonGroup object – Declares method add to add a JRadioButton to group – Usually represents mutually exclusive options

133  1992-2007 Pearson Education, Inc. All rights reserved. 133 11.9.2 JRadioButton Event listener: – ItemListener – has the abstract method: itemStateChanged – Taking an event ItemEvent When on of the radio buttons is selected an – ItemEvent object is created that cantain information about the event: Source – The ItemListener infterface’s itemStateChanged method process that event taking an ItemEvent object as parameter

134  1992-2007 Pearson Education, Inc. All rights reserved. 134 Common Programming Error 11.3 Adding a ButtonGroup object (or an object of any other class that does not derive from Component ) to a container results in a compilation error.

135  1992-2007 Pearson Education, Inc. All rights reserved. 135 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class RadioButton0 { public static void main(String[] args) { RadioButtonFrame0 radioButtonFrame0 = new RadioButtonFrame0(“Radio Button Example"); radioButtonFrame0.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE); radioButtonFrame0.setSize(400, 200); radioButtonFrame0.setVisible(true); }

136  1992-2007 Pearson Education, Inc. All rights reserved. 136 class RadioButton0 extends jFrame { private JLabel label; private JRadioButton maleRadioButton; private JRadioButton femaleRadioButton; private ButtonGroup genderGrup; new;

137  1992-2007 Pearson Education, Inc. All rights reserved. 137 public RadioButtonFrame0(String title) { super(title); setLayout(new FlowLayout()); label = new JLabel(“gender is female"); add(label); maleRadioButton = new JRadioButton(“Male",false); femaleRadioButton = new JRadioButton(“Female",true); genderGrup = new ButtonGroup(); genderGrup.add(maleRadioButton); genderGrup.add(femaleRadioButton);

138  1992-2007 Pearson Education, Inc. All rights reserved. 138 add(mleRadioButton); add(femaleRadioButton); RadioButtonHandler handler = new RadioButtonHandler(); maleRadioButton.addItemListener(handler); femaleRadioButton.addItemListener(handler); } // end of constructor

139  1992-2007 Pearson Education, Inc. All rights reserved. 139 private class RadioButtonHandler implements ItemListener { public void itemStateChanged(ItemEvent event) { if(event.getSource() instanceof JRadioButton) { if(boyRadioButton.isSelected()) label.setText(“gender is male"); if(girlRadioButton.isSelected()) label.setText(“gender is female"); } } // end ItemSteteChanged method } // end Handler inner class } // end RadioButtonFrame0 class

140  1992-2007 Pearson Education, Inc. All rights reserved. 140

141  1992-2007 Pearson Education, Inc. All rights reserved. 141 Outline RadioButtonFrame.java (1 of 3)

142  1992-2007 Pearson Education, Inc. All rights reserved. 142 Outline RadioButtonFrame.java (1 of 3)

143  1992-2007 Pearson Education, Inc. All rights reserved. 143 Outline RadioButtonFrame.java (2 of 3)

144  1992-2007 Pearson Education, Inc. All rights reserved. 144 Outline RadioButtonFrame.java (3 of 3)

145  1992-2007 Pearson Education, Inc. All rights reserved. 145 Outline RadioButtonTest.java

146  1992-2007 Pearson Education, Inc. All rights reserved. 146 Outline RadioButtonTest.java

147  1992-2007 Pearson Education, Inc. All rights reserved. 147 Another version of the RadioButtonFrame class // Changing fornt of a text with radio buttons // modified version of books example import javax.swing.*; import java.awt.*; import java.awt.event.*; public class RadioButtonFrame extends JFrame { private JTextField textField; private JRadioButton italicRadioButton; private JRadioButton boldRadioButton; private JRadioButton italicveboldRadioButton; private JRadioButton plainRadioButton; private ButtonGroup fontGrup;

148  1992-2007 Pearson Education, Inc. All rights reserved. 148 public RadioButtonFrame() { setLayout(new FlowLayout()); textField = new JTextField(“trail",20); textField.setFont(new Font("Serif",Font.PLAIN,14)); add(textField); boldRadioButton = new JRadioButton("Bold",false); italicRadioButton = new JRadioButton("Italic",false); italicveboldRadioButton = new JRadioButton("italic&bold",false); plainRadioButton = new JRadioButton("plain",true); fontGrup = new ButtonGroup(); fontGrup.add(boldRadioButton); fontGrup.add(italicRadioButton); fontGrup.add(italicveboldRadioButton); fontGrup.add(plainRadioButton);

149  1992-2007 Pearson Education, Inc. All rights reserved. 149 add(boldRadioButton); add(italicRadioButton); add(italicveboldRadioButton); add(plainRadioButton); RadioButtonHandler handler = new RadioButtonHandler(); boldRadioButton.addItemListener(handler); italicveboldRadioButton.addItemListener(handler); italicRadioButton.addItemListener(handler); plainRadioButton.addItemListener(handler); } // end of constructor

150  1992-2007 Pearson Education, Inc. All rights reserved. 150 private class RadioButtonHandler implements ItemListener { private int valFont = Font.PLAIN; private Font newFont; public void itemStateChanged(ItemEvent event) { if(event.getSource() instanceof JRadioButton) { if(boldRadioButton.isSelected()) valFont = Font.BOLD ; if(italicRadioButton.isSelected()) valFont = Font.ITALIC; if(italicveboldRadioButton.isSelected()) valFont = Font.ITALIC+Font.BOLD; if(plainRadioButton.isSelected()) valFont = Font.PLAIN; }

151  1992-2007 Pearson Education, Inc. All rights reserved. 151 newFont = new Font("Serif",valFont,14); textField.setFont(newFont); } // end method ItemSteteChanged } // end inner class RadioButtonHandler } // end class RadioButtonFrame

152  1992-2007 Pearson Education, Inc. All rights reserved. 152 11.10 JComboBox and Using an Anonymous Inner Class for Event Handling Combo box – Also called a drop-down list list of items from which user makes a single selection – Implemented by class JComboBox – generates ItemEvents or ActionEvents JCheckBox and JRadioButton – Each item in the list has an index – when an item is seleced generates ActionEvent

153  1992-2007 Pearson Education, Inc. All rights reserved. 153 some JComboBox methods setMaximumRowCount sets the maximum number of rows shown at once JComboBox provides a scrollbar and up and down arrows to traverse list Which item of in the displayed list is selected ? – How to get this information about the selected item? getSelectedIndex method of JComboBox class returns the selected index

154  1992-2007 Pearson Education, Inc. All rights reserved. 154 Constructors of JComboBox JComboBox() – creates a default empty combobox JComboBox(Object[] o) – creates a combobox that contains the elements in the specified array Example: – String letterGradess[] = {“AA”,”BA”,”BB”,”CB”,”CC”,”F”}; – JComboBox letterCombo = new JComboBox(letterGrades);

155  1992-2007 Pearson Education, Inc. All rights reserved. 155 getting what is selected int getSelectedIndex() – returns the index of the item selected Object getSelectedI tem() – returns the selected item

156  1992-2007 Pearson Education, Inc. All rights reserved. 156 Example of ComboBox Select an employee from a combobox and list her name, lastname and wage to a textArea The ComboBoxFrame class that extends from JFrame: – names,last names and wages of 5 employees – a combobox and a textArea – Select an employee from the combo and her name, lastname and wage are displayed in the textArea Here – the ActionEvent is generated when an item is selected – ActionListener is implemented – actionPerformed method is invoked

157  1992-2007 Pearson Education, Inc. All rights reserved. 157 The test class import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ComboBox0 { public static void main(String[] args) { ComboBoxFrame comboBoxFrame = new ComboBoxFrame(); comboBoxFrame.setDefaultCloseOperation(JFrame.EXIT_ON_C LOSE); comboBoxFrame.setSize(400, 200); comboBoxFrame.setVisible(true); }

158  1992-2007 Pearson Education, Inc. All rights reserved. 158 ComboBoxFrame class class ComboBoxFrame extends JFrame { private JComboBox combo; private JTextArea status; String names[] = {"Ali","Burak","Can","Derya","Elif"}; String lastNames[] = {"Or","Pamuk","Ulaş","Tınaz","Yılmaz"}; int wages[] = {1000,1500,1200,800,900}; public ComboBoxFrame() { setLayout(new FlowLayout(FlowLayout.LEFT,10,30)); combo = new JComboBox(names); status = new JTextArea(7,25); add(combo); add(status); ComboBoxHandler handler = new ComboBoxHandler(); combo.addActionListener(handler); } // end constructor

159  1992-2007 Pearson Education, Inc. All rights reserved. 159 ComboBoxHandler inner class private class ComboBoxHandler implements ActionListener { public void actionPerformed(ActionEvent e) { int i = combo.getSelectedIndex(); status.setText(""); status.append("Name:"+names[i]+"\n"); status.append("LastName:"+lastNames[i]+"\n"); status.append("Wage:"+wages[i]); } // end method } // end inner class ComboBoxHandler } // end class ComboBoxFrame

160  1992-2007 Pearson Education, Inc. All rights reserved. 160 output of the program

161  1992-2007 Pearson Education, Inc. All rights reserved. 161 Anonymous Inner Class for Event Handling Anonymous inner class – Special form of inner class – Declared without a name – Typically appears inside a method call – Has limited access to local variables

162  1992-2007 Pearson Education, Inc. All rights reserved. 162 Anonymous Inner Class for Event Handling – extends a superclass or implements an interface – uses either no arg –default constructor of its superclass or if imlements an interface uses Objcect() – declared like that: new SuperClass name or Interface name () { imlements abstract method s of superclass or all methods of the interface or can have its own methods }

163  1992-2007 Pearson Education, Inc. All rights reserved. 163 ComboBoxFrame class with an anonymous class // with anonumous class implementatition class ComboBoxFrame extends JFrame { private JComboBox combo; private JTextArea status; String names[] = {"Ali","Burak","Can","Derya","Elif"}; String lastNames[] = {"Or","Pamuk","Ulaş","Tınaz","Yılmaz"}; int wages[] = {1000,1500,1200,800,900}; public ComboBoxFrame() { setLayout(new FlowLayout(FlowLayout.LEFT,10,30)); combo = new JComboBox(names); status = new JTextArea(7,25); add(combo); add(status);

164  1992-2007 Pearson Education, Inc. All rights reserved. 164 the anonymous class combo.addActionListener( // invoke method new ActionListener() { // anonymous class begins public void actionPerformed(ActionEvent e) { int i = combo.getSelectedIndex(); status.setText(""); status.append("Name:"+names[i]+"\n"); status.append("LastName:"+lastNames[i]+"\n"); status.append("Wage:"+wages[i]); } // end method } // end anonymous class ComboBoxHandler ); // end invoking addActionListener method } // end constructor } // end class ComboBoxFrame

165  1992-2007 Pearson Education, Inc. All rights reserved. 165 11.10 JComboBox and Using an Anonymous Inner Class for Event Handling following example – list of four image file names – user selects one and the corresponding icın is displayed as a label Names of the images are held in a String array – lines 17-18 Images files are stored in the same directory are obtained and stored in array of ImageIcons – lines 19-23 JComboBox constructor accepts an array parameter – the names of images to be listed – a selction is to be made

166  1992-2007 Pearson Education, Inc. All rights reserved. 166 11.10 JComboBox and Using an Anonymous Inner Class for Event Handling – setMaximumRowCount sets the maximum number of rows shown at once – JComboBox provides a scrollbar and up and down arrows to traverse list at line 49: – label = new JLabel(icons[0]); lablel is instantiated with a constructor accepting an Icon object as teh parameter – no text is set

167  1992-2007 Pearson Education, Inc. All rights reserved. 167 Look-and-Feel Observation 11.11 Set the maximum row count for a JComboBox to a number of rows that prevents the list from expanding outside the bounds of the window in which it is used. This configuration will ensure that the list displays correctly when it is expanded by the user.

168  1992-2007 Pearson Education, Inc. All rights reserved. 168 Using an Anonymous Inner Class for Event Handling Anonymous inner class – Special form of inner class – Declared without a name – Typically appears inside a method call – Has limited access to local variables

169  1992-2007 Pearson Education, Inc. All rights reserved. 169 Using an Anonymous Inner Class for Event Handling Anonymous inner class – Special form of inner class – Declared without a name – Typically appears inside a method call – Has limited access to local variables

170  1992-2007 Pearson Education, Inc. All rights reserved. 170 Using an Anonymous Inner Class for Event Handling – extends a superclass or implements an interface – uses either no arg –default constructor of its superclass or if imlements an interface uses Objcect() – declared like that: new SuperClass name or Interface name () { imlements abstract method s of superclass or all methods of the interface or can have its own methods }

171  1992-2007 Pearson Education, Inc. All rights reserved. 171 Outline ComboBoxFrame.java (1 of 2)

172  1992-2007 Pearson Education, Inc. All rights reserved. 172 Outline ComboBoxFrame.java (1 of 2)

173  1992-2007 Pearson Education, Inc. All rights reserved. 173 Outline ComboBoxFrame.java (1 of 2)

174  1992-2007 Pearson Education, Inc. All rights reserved. 174 Outline ComboBoxFrame.java (1 of 2)

175  1992-2007 Pearson Education, Inc. All rights reserved. 175 Outline ComboBoxFrame.java (1 of 2)

176  1992-2007 Pearson Education, Inc. All rights reserved. 176 Outline ComboBoxTest.java

177  1992-2007 Pearson Education, Inc. All rights reserved. 177 Outline Scrollbar to scroll through the items in the list scroll arrowsscroll box

178  1992-2007 Pearson Education, Inc. All rights reserved. 178 Software Engineering Observation 11.5 An anonymous inner class declared in a method can access the instance variables and methods of the top-level class object that declared it, as well as the method’s final local variables, but cannot access the method’s non- final variables.

179  1992-2007 Pearson Education, Inc. All rights reserved. 179 Software Engineering Observation 11.6 Like any other class, when an anonymous inner class implements an interface, the class must implement every method in the interface.

180  1992-2007 Pearson Education, Inc. All rights reserved. 180 imagesJComboBox.addItemListener( new ItemListener() // anonymous inner class { // handle JComboBox event public void itemStateChanged( ItemEvent event ) { // determine whether check box selected if ( event.getStateChange() == ItemEvent.SELECTED ) label.setIcon( icons[ imagesJComboBox.getSelectedIndex() ] ); } // end method itemStateChanged } // end anonymous inner class ); // end call to addItemListener

181  1992-2007 Pearson Education, Inc. All rights reserved. 181 imagesJComboBox.addItemListener( new ItemListener() { /* body of anonymous inner class no class name ItemListener is the interface the anonymous inner class implements create an object no reference is defined even the class of the object has no name but imlements an interface */ } // end anonymous inner class ); // end call to addItemListener

182  1992-2007 Pearson Education, Inc. All rights reserved. 182 imagesJComboBox.addItemListener( new ItemListener() { // handle JComboBox event public void itemStateChanged( ItemEvent event ) { // indisde the method } // end method itemStateChanged } // end anonymous inner class ); // end call to addItemListener

183  1992-2007 Pearson Education, Inc. All rights reserved. 183 public void itemStateChanged( ItemEvent event ) { // determine whether check box selected if ( event.getStateChange() == ItemEvent.SELECTED ) label.setIcon( icons[ imagesJComboBox.getSelectedIndex() ] ); } // end method itemStateChanged the check box is seleced if event’s getStateChange() nethod returns a constant which is equal to the ItemEvent.SELECED constant what to do then !

184  1992-2007 Pearson Education, Inc. All rights reserved. 184 if ( event.getStateChange() == ItemEvent.SELECTED ) label.setIcon( icons[ imagesJComboBox.getSelectedIndex() ] ); the getSelectedIndex() method of the JCheckBox class returns the index of the item seleced label.setIcon(Icon ic) method sets the icon of label its argument is the Icon object to be added to the label here the Icon object is one of the members of the icons array whose index is seleced longer version is given in next slide

185  1992-2007 Pearson Education, Inc. All rights reserved. 185 inside the if statement could be written in another wet – avşt longer if ( event.getStateChange() == ItemEvent.SELECTED ) { int i = imagesJComboBox.getSelectedIndex(); label.setIcon( icons[ i] ); } the getSelectedIndex() method of the JCheckBox class returns the index of the item seleced- here int i label.setIcon(Icon ic) method sets the icon of label its argument is the Icon object to be added to the label here the Icon object is one of the members of the icons array whose index is seleced - icons[i]

186  1992-2007 Pearson Education, Inc. All rights reserved. 186 11.11 JList List – Displays a series of items from which the user may select one or more items – Implemented by class JList – Allows for single-selection lists or multiple-selection lists – A ListSelectionEvent occurs when an item is selected Handled by a ListSelectionListener and passed to method valueChanged

187  1992-2007 Pearson Education, Inc. All rights reserved. 187 11.11 JList In this example a list of 13 colors are created – when a color is selected a ListSelectionEvent occurs – the color of the background changes to the color seleced list of names of colors is argument to the constructor of JList object colorList

188  1992-2007 Pearson Education, Inc. All rights reserved. 188 Outline ListFrame.java (1 of 2)

189  1992-2007 Pearson Education, Inc. All rights reserved. 189 Outline ListFrame.java (1 of 2)

190  1992-2007 Pearson Education, Inc. All rights reserved. 190 Outline ListFrame.java (2 of 2)

191  1992-2007 Pearson Education, Inc. All rights reserved. 191 Outline ListTest.java

192  1992-2007 Pearson Education, Inc. All rights reserved. 192 colorJList.addListSelectionListener( new ListSelectionListener() { public void valueChanged( ListSelectionEvent event ) { getContentPane().setBackground( colors[ colorJList.getSelectedIndex() ] ); } // end method valueChanged } // end anonymous inner class ); // end call to addListSelectionListener } // end ListFrame constructor } // end class ListFrame

193  1992-2007 Pearson Education, Inc. All rights reserved. 193 colorJList.addListSelectionListener( new ListSelectionListener() { // body of anonymous inner class //has the valueChanged method } // end anonymous inner class ); // end call to addListSelectionListener this inner class imlements ListSelectionListener

194  1992-2007 Pearson Education, Inc. All rights reserved. 194 colorJList.addListSelectionListener( new ListSelectionListener() { public void valueChanged( ListSelectionEvent event ) { // ListSelectionEvent is processed in that method } // end method valueChanged } // end anonymous inner class ); // end call to addListSelectionListener this inner class imlements ListSelectionListener its value changed method is to be imlemented the event type is ListSelection

195  1992-2007 Pearson Education, Inc. All rights reserved. 195 public void valueChanged( ListSelectionEvent even) { getContentPane().setBackground( colors[ colorJList.getSelectedIndex() ] ); } // end method valueChanged what the valueChaned method does? getSelectedIndex() method of a JList class returns the index selected setBackground method set

196  1992-2007 Pearson Education, Inc. All rights reserved. 196 public void valueChanged( ListSelectionEvent even) { int i = colorJList.getSelectedIndex(); getContentPane().setBackground(colors[i]); } // end method valueChanged A two step version of the same method setBackground method sets the color of background the color is one of the members of the color array method getContentPane returns a reference to the JFrames content Pane then its setBackground method is called

197  1992-2007 Pearson Education, Inc. All rights reserved. 197 11.12 Multiple-Selection Lists Multiple-selection list – Enables users to select many items – Single interval selection allows only a continuous range of items – Multiple interval selection allows any set of elements to be selected

198  1992-2007 Pearson Education, Inc. All rights reserved. 198 Simple Example Select products from a list display in a textArea: – products selected, their prices – total payment

199  1992-2007 Pearson Education, Inc. All rights reserved. 199 Test class List0 import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.event.*; public class List0 { public static void main(String[] args) { ListFrame0 listFrame = new ListFrame0(); listFrame.setDefaultCloseOperation(JFrame.EXIT_ON_ CLOSE); listFrame.setSize(400, 200); listFrame.setVisible(true); }

200  1992-2007 Pearson Education, Inc. All rights reserved. 200 class ListFrame0 class ListFrame0 extends JFrame { private JList list; private JButton button; private JTextArea purchased; private String products[] = {"book","tea","cheese","bread","milk"}; private int prices[] = {10,12,20,15,2}; private int total; public ListFrame0() { setLayout(new FlowLayout()); list = new JList(products); list.setVisibleRowCount(3); list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); button = new JButton("add"); purchased = new JTextArea(7,25);

201  1992-2007 Pearson Education, Inc. All rights reserved. 201 class ListFrame0 (cont.) add(list); add(new JScrollPane(list)); add(button); add(purchased); button.addActionListener(new ListHandler()); } // end constructor

202  1992-2007 Pearson Education, Inc. All rights reserved. 202 inner class ListHandler private class ListHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if(e.getSource()==button) { total = 0; purchased.setText("purchased:"); int choice[] = list.getSelectedIndices(); for(int i = 0;i < choice.length;i++) { purchased.append("\n\t"+products[choice[i]]); purchased.append("\t"+prices[choice[i]]); total += prices[choice[i]]; } // end for purchased.append("\ntotal:\t"+total); } // end if } // end method actionPerformed } // end inner class ListHandler } // end class ListFrame0

203  1992-2007 Pearson Education, Inc. All rights reserved. 203 output of the program

204  1992-2007 Pearson Education, Inc. All rights reserved. 204 Outline Multiple SelectionFrame.java (1 of 3)

205  1992-2007 Pearson Education, Inc. All rights reserved. 205 Outline Multiple SelectionFrame.java (2 of 3)

206  1992-2007 Pearson Education, Inc. All rights reserved. 206 Outline Multiple SelectionFrame.java (3 of 3)

207  1992-2007 Pearson Education, Inc. All rights reserved. 207 Outline Multiple SelectionTest.java

208  1992-2007 Pearson Education, Inc. All rights reserved. 208 copyJButton = new JButton( "Copy >>>" ); // create copy button copyJButton.addActionListener( new ActionListener() // anonymous inner class { // handle button event public void actionPerformed( ActionEvent event ) { // place selected values in copyJList copyJList.setListData( colorJList.getSelectedValues() ); } // end method actionPerformed } // end anonymous inner class ); // end call to addActionListener

209  1992-2007 Pearson Education, Inc. All rights reserved. 209 public void actionPerformed( ActionEvent event ) { // place selected values in copyJList copyJList.setListData( colorJList.getSelectedValues() ); } // end method actionPerformed colorJList.getSelectedValues() getSelectedValues() method called over colorList object returns array of objects selected by the user setListData method called on copyList get this array as an argument seting its list elements

210  1992-2007 Pearson Education, Inc. All rights reserved. 210 11.13 Mouse Event Handling Mouse events – Create a MouseEvent object – Handled by MouseListener s and MouseMotionListener s – MouseInputListener combines the two interfaces

211  1992-2007 Pearson Education, Inc. All rights reserved. 211 Fig. 11.27 | MouseListener and MouseMotionListener interface methods. (Part 1 of 2.)

212  1992-2007 Pearson Education, Inc. All rights reserved. 212 Fig. 11.27 | MouseListener and MouseMotionListener interface methods. (Part 2 of 2.)

213  1992-2007 Pearson Education, Inc. All rights reserved. 213 Look-and-Feel Observation 11.12 Method calls to mouseDragged and mouseReleased are sent to the MouseMotionListener for the Component on which a mouse drag operation started. Similarly, the mouseReleased method call at the end of a drag operation is sent to the MouseListener for the Component on which the drag operation started.

214  1992-2007 Pearson Education, Inc. All rights reserved. 214 Outline MouseTracker Frame.java (1 of 4)

215  1992-2007 Pearson Education, Inc. All rights reserved. 215 Outline MouseTracker Frame.java (2 of 4)

216  1992-2007 Pearson Education, Inc. All rights reserved. 216 Outline MouseTracker Frame.java (2 of 4)

217  1992-2007 Pearson Education, Inc. All rights reserved. 217 Outline MouseTracker Frame.java (3 of 4)

218  1992-2007 Pearson Education, Inc. All rights reserved. 218 Outline MouseTracker Frame.java (4 of 4)

219  1992-2007 Pearson Education, Inc. All rights reserved. 219 Outline MouseTracker Frame.java (1 of 2)

220  1992-2007 Pearson Education, Inc. All rights reserved. 220 Outline MouseTracker Frame.java (2 of 2)

221  1992-2007 Pearson Education, Inc. All rights reserved. 221 // Fig. 11.28: MouseTrackerFrame.java // Demonstrating mouse events. import java.awt.Color; import java.awt.BorderLayout; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class MouseTrackerFrame extends JFrame { private JPanel mousePanel; // panel in which mouse events will occur private JLabel statusBar; // label that displays event information

222  1992-2007 Pearson Education, Inc. All rights reserved. 222 // MouseTrackerFrame constructor sets up GUI and // registers mouse event handlers public MouseTrackerFrame() { super( "Demonstrating Mouse Events" ); mousePanel = new JPanel(); // create panel mousePanel.setBackground( Color.WHITE ); // set background color add( mousePanel, BorderLayout.CENTER ); // add panel to JFrame statusBar = new JLabel( "Mouse outside JPanel" ); add( statusBar, BorderLayout.SOUTH ); // add label to JFrame // create and register listener for mouse and mouse motion events MouseHandler handler = new MouseHandler(); mousePanel.addMouseListener( handler ); mousePanel.addMouseMotionListener( handler ); } // end MouseTrackerFrame constructor

223  1992-2007 Pearson Education, Inc. All rights reserved. 223 // private class MouseHandler implements MouseListener, MouseMotionListener { // MouseListener event handlers // handle event when mouse released immediately after press public void mouseClicked( MouseEvent event ) { statusBar.setText( String.format( "Clicked at [%d, %d]", event.getX(), event.getY() ) ); } // end method mouseClicked // handle event when mouse pressed public void mousePressed( MouseEvent event ) { statusBar.setText( String.format( "Pressed at [%d, %d]", event.getX(), event.getY() ) ); } // end method mousePressed

224  1992-2007 Pearson Education, Inc. All rights reserved. 224 // handle event when mouse released after dragging public void mouseReleased( MouseEvent event ) { statusBar.setText( String.format( "Released at [%d, %d]", event.getX(), event.getY() ) ); } // end method mouseReleased // handle event when mouse enters area public void mouseEntered( MouseEvent event ) { statusBar.setText( String.format( "Mouse entered at [%d, %d]", event.getX(), event.getY() ) ); mousePanel.setBackground( Color.GREEN ); } // end method mouseEntered // handle event when mouse exits area public void mouseExited( MouseEvent event ) { statusBar.setText( "Mouse outside JPanel" ); mousePanel.setBackground( Color.WHITE ); } // end method mouseExited

225  1992-2007 Pearson Education, Inc. All rights reserved. 225 // MouseMotionListener event handlers // handle event when user drags mouse with button pressed public void mouseDragged( MouseEvent event ) { statusBar.setText( String.format( "Dragged at [%d, %d]", event.getX(), event.getY() ) ); } // end method mouseDragged // handle event when user moves mouse public void mouseMoved( MouseEvent event ) { statusBar.setText( String.format( "Moved at [%d, %d]", event.getX(), event.getY() ) ); } // end method mouseMoved } // end inner class MouseHandler } // end class MouseTrackerFrample

226  1992-2007 Pearson Education, Inc. All rights reserved. 226 11.14 Adapter Classes Adapter class – Implements event listener interface – Provides default implementation for all event-handling methods

227  1992-2007 Pearson Education, Inc. All rights reserved. 227 Software Engineering Observation 11.7 When a class implements an interface, the class has an “is a” relationship with that interface. All direct and indirect subclasses of that class inherit this interface. Thus, an object of a class that extends an event-adapter class is an object of the corresponding event-listener type (e.g., an object of a subclass of MouseAdapter is a MouseListener ).

228  1992-2007 Pearson Education, Inc. All rights reserved. 228 Extending MouseAdapter MouseAdapter – Adapter class for MouseListener and MouseMotionListener interfaces – Extending class allows you to override only the methods you wish to use

229  1992-2007 Pearson Education, Inc. All rights reserved. 229 Common Programming Error 11.4 If you extend an adapter class and misspell the name of the method you are overriding, your method simply becomes another method in the class. This is a logic error that is difficult to detect, since the program will call the empty version of the method inherited from the adapter class.

230  1992-2007 Pearson Education, Inc. All rights reserved. 230 Fig. 11.30 | Event-adapter classes and the interfaces they implement in package java.awt.event.

231  1992-2007 Pearson Education, Inc. All rights reserved. 231 Outline MouseDetails Frame.java (1 of 2)

232  1992-2007 Pearson Education, Inc. All rights reserved. 232 Outline MouseDetails Frame.java (2 of 2)

233  1992-2007 Pearson Education, Inc. All rights reserved. 233 Outline MouseDetails.java (1 of 2)

234  1992-2007 Pearson Education, Inc. All rights reserved. 234 Outline MouseDetails.java (2 of 2)

235  1992-2007 Pearson Education, Inc. All rights reserved. 235 import java.awt.BorderLayout; import java.awt.Graphics; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JLabel; public class MouseDetailsFrame extends JFrame { private String details; // String representing private JLabel statusBar; // JLabel that appears at bottom of window // constructor sets title bar String and register mouse listener public MouseDetailsFrame() { super( "Mouse clicks and buttons" ); statusBar = new JLabel( "Click the mouse" ); add( statusBar, BorderLayout.SOUTH ); addMouseListener( new MouseClickHandler() ); // add handler } // end MouseDetailsFrame constructor

236  1992-2007 Pearson Education, Inc. All rights reserved. 236 // inner class to handle mouse events private class MouseClickHandler extends MouseAdapter { // handle mouse click event and determine which button was pressed public void mouseClicked( MouseEvent event ) { int xPos = event.getX(); // get x position of mouse int yPos = event.getY(); // get y position of mouse details = String.format( "Clicked %d time(s)", event.getClickCount() ); if ( event.isMetaDown() ) // right mouse button details += " with right mouse button"; else if ( event.isAltDown() ) // middle mouse button details += " with center mouse button"; else // left mouse button details += " with left mouse button"; statusBar.setText( details ); // display message in statusBar } // end method mouseClicked } // end private inner class MouseClickHandler } // end class MouseDetailsFrame

237  1992-2007 Pearson Education, Inc. All rights reserved. 237 11.15 JPanel Subclass for Drawing with the Mouse Overriding class JPanel – Provides a dedicated drawing area

238  1992-2007 Pearson Education, Inc. All rights reserved. 238 Fig. 11.33 | InputEvent methods that help distinguish among left-, center- and right-mouse-button clicks.

239  1992-2007 Pearson Education, Inc. All rights reserved. 239 Method paintComponent – Draws on a Swing component – Overriding method allows you to create custom drawings – Must call superclass method first when overridden

240  1992-2007 Pearson Education, Inc. All rights reserved. 240 Look-and-Feel Observation 11.13 Most Swing GUI components can be transparent or opaque. If a Swing GUI component is opaque, its background will be cleared when its paintComponent method is called. Only opaque components can display a customized background color. JPanel objects are opaque by default.

241  1992-2007 Pearson Education, Inc. All rights reserved. 241 Error-Prevention Tip 11.1 In a JComponent subclass’s paintComponent method, the first statement should always be a call to the superclass’s paintComponent method to ensure that an object of the subclass displays correctly.

242  1992-2007 Pearson Education, Inc. All rights reserved. 242 Common Programming Error 11.5 If an overridden paintComponent method does not call the superclass’s version, the subclass component may not display properly. If an overridden paintComponent method calls the superclass’s version after other drawing is performed, the drawing will be erased.

243  1992-2007 Pearson Education, Inc. All rights reserved. 243 Defining the Custom Drawing Area Customized subclass of JPanel – Provides custom drawing area – Class Graphics is used to draw on Swing components – Class Point represents an x-y coordinate

244  1992-2007 Pearson Education, Inc. All rights reserved. 244 Outline PaintPanel.java (1 of 2) Create array of Point s

245  1992-2007 Pearson Education, Inc. All rights reserved. 245 Outline PaintPanel.java (2 of 2) Anonymous inner class for event handling Override mouseDragged method Get location of mouse cursor Repaint the JFrame Get the x and y-coordinates of the Point

246  1992-2007 Pearson Education, Inc. All rights reserved. 246 Look-and-Feel Observation 11.14 Calling repaint for a Swing GUI component indicates that the component should be refreshed on the screen as soon as possible. The background of the GUI component is cleared only if the component is opaque. JComponent method setOpaque can be passed a boolean argument indicating whether the component is opaque ( true ) or transparent ( false ).

247  1992-2007 Pearson Education, Inc. All rights reserved. 247 Look-and-Feel Observation 11.15 Drawing on any GUI component is performed with coordinates that are measured from the upper-left corner (0, 0) of that GUI component, not the upper-left corner of the screen.

248  1992-2007 Pearson Education, Inc. All rights reserved. 248 Outline Painter.java (1 of 2) Create instance of custom drawing panel

249  1992-2007 Pearson Education, Inc. All rights reserved. 249 Outline Painter.java (2 of 2)

250  1992-2007 Pearson Education, Inc. All rights reserved. 250 11.16 Key-Event Handling KeyListener interface – For handling KeyEvent s – Declares methods keyPressed, keyReleased and keyTyped

251  1992-2007 Pearson Education, Inc. All rights reserved. 251 Outline KeyDemoFrame.java (1 of 3)

252  1992-2007 Pearson Education, Inc. All rights reserved. 252 Outline KeyDemoFrame.java (2 of 3)

253  1992-2007 Pearson Education, Inc. All rights reserved. 253 Outline KeyDemoFrame.java (3 of 3)

254  1992-2007 Pearson Education, Inc. All rights reserved. 254 Outline KeyDemo.java (1 of 2)

255  1992-2007 Pearson Education, Inc. All rights reserved. 255 Outline KeyDemo.java (1 of 2)

256  1992-2007 Pearson Education, Inc. All rights reserved. 256 import java.awt.Color; import java.awt.event.KeyListener; import java.awt.event.KeyEvent; import javax.swing.JFrame; import javax.swing.JTextArea; public class KeyDemoFrame extends JFrame implements KeyListener { private String line1 = ""; // first line of textarea private String line2 = ""; // second line of textarea private String line3 = ""; // third line of textarea private JTextArea textArea; // textarea to display output

257  1992-2007 Pearson Education, Inc. All rights reserved. 257 // KeyDemoFrame constructor public KeyDemoFrame() { super( "Demonstrating Keystroke Events" ); textArea = new JTextArea( 10, 15 ); // set up JTextArea textArea.setText( "Press any key on the keyboard..." ); textArea.setEnabled( false ); // disable textarea textArea.setDisabledTextColor( Color.BLACK ); // set text color add( textArea ); // add textarea to JFrame addKeyListener( this ); // allow frame to process key event } // end KeyDemoFrame constructor

258  1992-2007 Pearson Education, Inc. All rights reserved. 258 // handle press of any key public void keyPressed( KeyEvent event ) { line1 = String.format( "Key pressed: %s", event.getKeyText( event.getKeyCode() ) ); // output pressed key setLines2and3( event ); // set output lines two and three } // end method keyPressed // handle release of any key public void keyReleased( KeyEvent event ) { line1 = String.format( "Key released: %s", event.getKeyText( event.getKeyCode() ) ); // output released key setLines2and3( event ); // set output lines two and three } // end method keyReleased // handle press of an action key public void keyTyped( KeyEvent event ) { line1 = String.format( "Key typed: %s", event.getKeyChar() ); setLines2and3( event ); // set output lines two and three } // end method keyTyped

259  1992-2007 Pearson Education, Inc. All rights reserved. 259 // set second and third lines of output private void setLines2and3( KeyEvent event ) { line2 = String.format( "This key is %san action key", ( event.isActionKey() ? "" : "not " ) ); String temp = event.getKeyModifiersText( event.getModifiers() ); line3 = String.format( "Modifier keys pressed: %s", ( temp.equals( "" ) ? "none" : temp ) ); // output modifiers textArea.setText( String.format( "%s\n%s\n%s\n", line1, line2, line3 ) ); // output three lines of text } // end method setLines2and3 } // end class KeyDemoFrame

260  1992-2007 Pearson Education, Inc. All rights reserved. 260 11.17 Layout Managers Layout managers – Provided to arrange GUI components in a container – Provide basic layout capabilities – Implement the interface LayoutManager – class Container’s setLayout method takes an object that imlements the LayoutManager interface

261  1992-2007 Pearson Education, Inc. All rights reserved. 261 11.17 Layout Managers There are three ways to arrange components – Absolute possitioning: Setting Container’s layout to null Coordinates of the component with respect to the upper left possition of the container Specify the size of the component as well – Layout Managers: Easier then (1) but Lose some contro – size or possitioning – Visual programming in an IDe:

262  1992-2007 Pearson Education, Inc. All rights reserved. 262 Look-and-Feel Observation 11.16 Most Java programming environments provide GUI design tools that help a programmer graphically design a GUI; the design tools then write the Java code to create the GUI. Such tools often provide greater control over the size, position and alignment of GUI components than do the built-in layout managers.

263  1992-2007 Pearson Education, Inc. All rights reserved. 263 Look-and-Feel Observation 11.17 It is possible to set a Container ’s layout to null, which indicates that no layout manager should be used. In a Container without a layout manager, the programmer must position and size the components in the given container and take care that, on resize events, all components are repositioned as necessary. A component’s resize events can be processed by a ComponentListener.

264  1992-2007 Pearson Education, Inc. All rights reserved. 264 11.17.1 FlowLayout FlowLayout – Simplest layout manager – Components are placed left to right in the order they are added – Components can be left aligned, centered or right aligned

265  1992-2007 Pearson Education, Inc. All rights reserved. 265 Fig. 11.38 | Layout managers.

266  1992-2007 Pearson Education, Inc. All rights reserved. 266 Outline FlowLayoutFrame.java (1 of 3)

267  1992-2007 Pearson Education, Inc. All rights reserved. 267 Outline FlowLayoutFrame.java (2 of 3)

268  1992-2007 Pearson Education, Inc. All rights reserved. 268 Outline FlowLayoutFrame.java (2 of 3)

269  1992-2007 Pearson Education, Inc. All rights reserved. 269 Outline FlowLayoutFrame.java (3 of 3)

270  1992-2007 Pearson Education, Inc. All rights reserved. 270 Outline FlowLayoutDemo.java (1 of 2)

271  1992-2007 Pearson Education, Inc. All rights reserved. 271 Outline FlowLayoutDemo.java (2 of 2)

272  1992-2007 Pearson Education, Inc. All rights reserved. 272 11.17.2 BorderLayout BorderLayout Arranges components into five regions – north, south, east, west and center Implements interface LayoutManager2 – A subinterface of LayoutManager Provides horizontal gap spacing and vertical gap spacing – Constructor: – BorderLayour(int hgap, int vgap);

273  1992-2007 Pearson Education, Inc. All rights reserved. 273 Example: Border Layout Enter two integers to two distinct textFields when pressed + button calcuate and display the sum as a label Components: – north: title - JLabel – west: first textField - jTextField – east: second testField - JTEextField – center: addition button -JButton – south: result apears - JLabel

274  1992-2007 Pearson Education, Inc. All rights reserved. 274 Test class import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.event.*; public class Border0 { public static void main(String[] args) { BorderFrame0 borderFrame0 = new BorderFrame0(); borderFrame0.setDefaultCloseOperation(JFrame.EXIT_ON_CL OSE); borderFrame0.setSize(400, 200); borderFrame0.setVisible(true); }

275  1992-2007 Pearson Education, Inc. All rights reserved. 275 class BorderFrame0 class BorderFrame0 extends JFrame { private JLabel title; private JLabel result; private JButton addition; private JTextField first; private JTextField second; public BorderFrame0() { setLayout(new BorderLayout(10,10)); title = new JLabel("Adding two integers"); result = new JLabel(" "); addition = new JButton("+"); first = new JTextField(10); second = new JTextField(10);

276  1992-2007 Pearson Education, Inc. All rights reserved. 276 class BorderFrame0 (cont.) add(title,BorderLayout.NORTH); add(addition,BorderLayout.CENTER); add(first,BorderLayout.WEST); add(second,BorderLayout.EAST); add(result,BorderLayout.SOUTH); ButtonHandler handler = new ButtonHandler(); addition.addActionListener(handler); } // end constructor

277  1992-2007 Pearson Education, Inc. All rights reserved. 277 inner class ButtonHandler private class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { int a,b,sum; if(e.getSource() == addition) { a = Integer.parseInt(first.getText()); b = Integer.parseInt(second.getText()); sum = a+b; result.setText(""+a+" + "+b+" = "+sum); } // end if } // end method actionPerformed } // end inner class ButtonHandler } // end class GridFrame0

278  1992-2007 Pearson Education, Inc. All rights reserved. 278 output of program

279  1992-2007 Pearson Education, Inc. All rights reserved. 279 Look-and-Feel Observation 11.18 Each container can have only one layout manager. Separate containers in the same application can use different layout managers.

280  1992-2007 Pearson Education, Inc. All rights reserved. 280 Look-and-Feel Observation 11.19 If no region is specified when adding a Component to a BorderLayout, the layout manager assumes that the Component should be added to region BorderLayout.CENTER.

281  1992-2007 Pearson Education, Inc. All rights reserved. 281 Common Programming Error 11.6 When more than one component is added to a region in a BorderLayout, only the last component added to that region will be displayed. There is no error that indicates this problem.

282  1992-2007 Pearson Education, Inc. All rights reserved. 282 Outline BorderLayout Frame.java (1 of 2)

283  1992-2007 Pearson Education, Inc. All rights reserved. 283 Outline BorderLayout Frame.java (1 of 2)

284  1992-2007 Pearson Education, Inc. All rights reserved. 284 Outline BorderLayout Frame.java (2 of 2)

285  1992-2007 Pearson Education, Inc. All rights reserved. 285 Outline BorderLayout Demo.java (1 of 2) horizontal gapvertical gap

286  1992-2007 Pearson Education, Inc. All rights reserved. 286 Outline BorderLayout Demo.java (2 of 2)

287  1992-2007 Pearson Education, Inc. All rights reserved. 287 11.17.3 GridLayout GridLayout Divides container into a grid Every component has the same width and height Constructors – GridLayout(int raws,int columns); – GridLayout(int raws,int columns,int hgap, int vgap);

288  1992-2007 Pearson Education, Inc. All rights reserved. 288 Example:GridLayour Create a GridLayout with 3 raws and 2 columns Enter name and lastname of a person when pressed OK, process these strings when pressed Cancel, erase these fields

289  1992-2007 Pearson Education, Inc. All rights reserved. 289 Test Class import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.event.*; public class GridLayout0 { public static void main(String[] args) { GridFrame0 gridFrame0 = new GridFrame0(); gridFrame0.setDefaultCloseOperation(JFrame.EXIT_ON _CLOSE); gridFrame0.setSize(400, 200); gridFrame0.setVisible(true); }

290  1992-2007 Pearson Education, Inc. All rights reserved. 290 class GridFrame0 class GridFrame0 extends JFrame { private JLabel name; private JLabel lastName; private JTextField nameText; private JTextField lastNameText; private JButton ok; private JButton cancel;

291  1992-2007 Pearson Education, Inc. All rights reserved. 291 class GridFrame0 (cont.) public GridFrame0() { setLayout(new GridLayout(3,2,5,5)); name = new JLabel("Name"); lastName = new JLabel("Last Name"); ok = new JButton("OK"); cancel = new JButton("Cancel"); nameText = new JTextField(10); lastNameText = new JTextField(20); add(name); add(nameText); add(lastName); add(lastNameText); add(ok); add(cancel); ButtonHandler handler = new ButtonHandler(); ok.addActionListener(handler); cancel.addActionListener(handler); } // end constructor

292  1992-2007 Pearson Education, Inc. All rights reserved. 292 inner class ButtonHanler private class ButtonHandler implements ActionListener { public void actionPerformed(ActionEvent e) { if(e.getSource() == ok) System.out.println(nameText.getText()+ ""+lastNameText.getText()); if(e.getSource() == cancel) { nameText.setText(""); lastNameText.setText(""); } // end if } // end method actionPerformed } // end inner class ButtonHandler } // end class GridFrame0

293  1992-2007 Pearson Education, Inc. All rights reserved. 293

294  1992-2007 Pearson Education, Inc. All rights reserved. 294 Outline GridLayout Frame.java (1 of 2)

295  1992-2007 Pearson Education, Inc. All rights reserved. 295 Outline GridLayout Frame.java (1 of 2)

296  1992-2007 Pearson Education, Inc. All rights reserved. 296 Outline GridLayout Frame.java (2 of 2)

297  1992-2007 Pearson Education, Inc. All rights reserved. 297 Outline GridLayoutDemo.java

298  1992-2007 Pearson Education, Inc. All rights reserved. 298 11.18 Using Panels to Manage More Complex Layouts Complex GUIs often require multiple panels to arrange their components properly

299  1992-2007 Pearson Education, Inc. All rights reserved. 299 Example Panels Entering and processing nemes and lastnames using panels

300  1992-2007 Pearson Education, Inc. All rights reserved. 300 Test class import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.event.*; public class Panel1 { public static void main(String[] args) { GridFrame1 gridFrame1 = new GridFrame1(); gridFrame1.setDefaultCloseOperation(JFrame.EXIT_O N_CLOSE); gridFrame1.setSize(400, 200); gridFrame1.setVisible(true); }

301  1992-2007 Pearson Education, Inc. All rights reserved. 301 class GridFrame1 class GridFrame1 extends JFrame implements ActionListener { private JLabel name; private JLabel lastName; private JTextField nameText; private JTextField lastNameText; private JButton ok; private JButton cancel; // create three panels private JPanel topPanel; private JPanel midPanel; private JPanel butomPanel;

302  1992-2007 Pearson Education, Inc. All rights reserved. 302 class GridFrame1 (cont.) public GridFrame1() { setLayout(new GridLayout(3,1,5,5)); name = new JLabel("Name"); lastName = new JLabel("Last Name"); ok = new JButton("OK"); cancel = new JButton("Cancel"); nameText = new JTextField(10); lastNameText = new JTextField(20); topPanel = new JPanel(); midPanel = new JPanel(); butomPanel = new JPanel();

303  1992-2007 Pearson Education, Inc. All rights reserved. 303 class GridFrame1 (cont.) // add components to relevant panels topPanel.add(name); topPanel.add(nameText); midPanel.add(lastName); midPanel.add(lastNameText); butomPanel.add(ok); butomPanel.add(cancel); // add panels to the frame add(topPanel); add(midPanel); add(butomPanel);

304  1992-2007 Pearson Education, Inc. All rights reserved. 304 inner class ButtonHandler ok.addActionListener(this); cancel.addActionListener(this); } // end constructor public void actionPerformed(ActionEvent e) { if(e.getSource() == ok) System.out.println(nameText.getText()+" "+lastNameText.getText()); if(e.getSource() == cancel) { nameText.setText(""); lastNameText.setText(""); } // end if } // end method actionPerformed } // end class GridFrame0

305  1992-2007 Pearson Education, Inc. All rights reserved. 305 output

306  1992-2007 Pearson Education, Inc. All rights reserved. 306 Outline PanelFrame.java (1 of 2)

307  1992-2007 Pearson Education, Inc. All rights reserved. 307 Outline PanelFrame.java (2 of 2)

308  1992-2007 Pearson Education, Inc. All rights reserved. 308 Outline PanelDemo.java

309  1992-2007 Pearson Education, Inc. All rights reserved. 309 Example Panels Add an action to the buttons when cliced a button display which one is cliced in a textField placed to the north

310  1992-2007 Pearson Education, Inc. All rights reserved. 310 class PanelFrame0 class PanelFrame0 extends JFrame implements ActionListener { private JPanel buttonJPanel; private JButton buttons[]; private JTextField textField; public PanelFrame0() { buttons = new JButton[5]; buttonJPanel = new JPanel(); textField = new JTextField(); buttonJPanel.setLayout(new GridLayout(1,buttons.length)); for(int i = 0;i < buttons.length;i++) { buttons[i] = new JButton("Button"+(i+1)); buttonJPanel.add(buttons[i]); }

311  1992-2007 Pearson Education, Inc. All rights reserved. 311 class PanelFrame0 (cont.) add(buttonJPanel,BorderLayout.SOUTH); add(textField,BorderLayout.NORTH); for(int i = 0;i < buttons.length;i++) buttons[i].addActionListener(this); } // end constructor

312  1992-2007 Pearson Education, Inc. All rights reserved. 312 inner class ButtonHandler public void actionPerformed(ActionEvent e) { String str = ""; textField.setText(""); for(int i = 0;i < buttons.length;i++) { if(e.getSource()==buttons[i]) str += "you clicked "+"Button"+(i+1); textField.setText(str); } // end for } // end method actionPerformed } // end class PanelFrame0

313  1992-2007 Pearson Education, Inc. All rights reserved. 313 output of the program

314  1992-2007 Pearson Education, Inc. All rights reserved. 314 11.19 JTextArea JTextArea – Provides an area for manipulating multiple lines of text Box container – Subclass of Container – Uses a BoxLayout layout manager

315  1992-2007 Pearson Education, Inc. All rights reserved. 315 Look-and-Feel Observation 11.20 To provide line-wrapping functionality for a JTextArea, invoke JTextArea method setLine- Wrap with a true argument.

316  1992-2007 Pearson Education, Inc. All rights reserved. 316 Outline TextAreaFrame.java (1 of 2)

317  1992-2007 Pearson Education, Inc. All rights reserved. 317 Outline TextAreaFrame.java (2 of 2)

318  1992-2007 Pearson Education, Inc. All rights reserved. 318 Outline TextAreaDemo.java (1 of 2)

319  1992-2007 Pearson Education, Inc. All rights reserved. 319 Outline TextAreaDemo.java (2 of 2)

320  1992-2007 Pearson Education, Inc. All rights reserved. 320 JScrollPane Scrollbar Policies JScrollPane has scrollbar policies – Horizontal policies Always ( HORIZONTAL_SCROLLBAR_ALWAYS ) As needed ( HORIZONTAL_SCROLLBAR_AS_NEEDED ) Never ( HORIZONTAL_SCROLLBAR_NEVER ) – Vertical policies Always ( VERTICAL_SCROLLBAR_ALWAYS ) As needed ( VERTICAL_SCROLLBAR_AS_NEEDED ) Never ( VERTICAL_SCROLLBAR_NEVER )

321  1992-2007 Pearson Education, Inc. All rights reserved. 321 Null Layout Edample

322  1992-2007 Pearson Education, Inc. All rights reserved. 322

323  1992-2007 Pearson Education, Inc. All rights reserved. 323 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class OverAll3 { public static void main(String[] args) { EmployeeFrame3 employeeFrame3 = new EmployeeFrame3(); employeeFrame3.setDefaultCloseOperation(JFram e.EXIT_ON_CLOSE); employeeFrame3.setSize(600, 500); employeeFrame3.setVisible(true); }

324  1992-2007 Pearson Education, Inc. All rights reserved. 324 class EmployeeFrame3 extends JFrame { private JButton ok; private JButton cancel; private JLabel name; private JLabel lastName; private JTextField empName; private JTextField empLName; private JTextArea status; private JPanel leftPanel; private JPanel centerPanel; private JPanel rightPanel; private JPanel typePanels[];

325  1992-2007 Pearson Education, Inc. All rights reserved. 325 private JLabel commision; private JLabel sales; private JLabel wage; private JLabel hours; private JTextField empCommision; private JTextField empSales; private JTextField empWage; private JTextField empHours; private String types[] = {"Commision","Hourly","Salaried"}; private JComboBox empType; private int selected=0; int i; // couter for loops

326  1992-2007 Pearson Education, Inc. All rights reserved. 326 public EmployeeFrame3() { setLayout(null); ok = new JButton("OK"); cancel = new JButton("CANCEL"); rightPanel= new JPanel(); rightPanel.setLayout(null); rightPanel.setSize(200,200); rightPanel.setLocation(450,150); ok.setSize(100,50); ok.setLocation(0,0); rightPanel.add(ok); rightPanel.add(cancel); cancel.setSize(100,50); cancel.setLocation(0,100); add(rightPanel);

327  1992-2007 Pearson Education, Inc. All rights reserved. 327 centerPanel= new JPanel(); centerPanel.setSize(250,250); centerPanel.setLocation(200,100); centerPanel.setLayout(new GridLayout(2,2,10,30)); name = new JLabel("Employee Name"); name.setLocation(0,0); name.setSize(80,20); lastName = new JLabel("Employee LastName"); empName = new JTextField(10); empLName = new JTextField(10); centerPanel.add(name); centerPanel.add(empName); centerPanel.add(lastName); centerPanel.add(empLName); add(centerPanel);

328  1992-2007 Pearson Education, Inc. All rights reserved. 328 // define and add status texarea status = new JTextArea(5,30); status.setLocation(50,350); status.setSize(200,100); add(status);

329  1992-2007 Pearson Education, Inc. All rights reserved. 329 // define and add left panel typeEmp = new JLabel("Emp Type:"); empType = new JComboBox(types); leftPanel = new JPanel(); leftPanel.setSize(150,50); leftPanel.setLocation(10,40); leftPanel.setLayout(new GridLayout(1,2,10,10)); leftPanel.add(typeEmp); leftPanel.add(empType); add(leftPanel);

330  1992-2007 Pearson Education, Inc. All rights reserved. 330 // create and edd typ panels typePanels = new JPanel[3]; for(i=0;i<typePanels.length;i++) {//create arry of panels typePanels[i] = new JPanel(); typePanels[i].setLayout(new GridLayout(0,2,10,10)); typePanels[i].setSize(150,80); typePanels[i].setLocation(10,200); add(typePanels[i]); typePanels[i].setVisible(false); } // end for loop

331  1992-2007 Pearson Education, Inc. All rights reserved. 331 // define and add components for type panels commision = new JLabel("Commision:"); sales = new JLabel("Sales:"); wage = new JLabel("Wage:"); hours = new JLabel("Hours:"); empCommision = new JTextField(10); empHours = new JTextField(10); empWage = new JTextField(10); empSales = new JTextField(10); typePanels[0].add(commision); typePanels[0].add(empCommision); typePanels[0].add(sales); typePanels[0].add(empSales);

332  1992-2007 Pearson Education, Inc. All rights reserved. 332 typePanels[1].add(hours); typePanels[1].add(empHours); typePanels[2].add(wage); typePanels[2].add(empWage); typePanels[0].setVisible(true); // registoring events to components ButtonHandler handler = new ButtonHandler(); ok.addActionListener(handler); cancel.addActionListener(handler); empType.addActionListener(handler); } // end constructor

333  1992-2007 Pearson Education, Inc. All rights reserved. 333

334  1992-2007 Pearson Education, Inc. All rights reserved. 334 private class ButtonHandler implements ActionListener { int j; double x; public void actionPerformed(ActionEvent e) { if(e.getSource() == ok) { status.setText(""); status.append("\nName :"+empName.getText()); status.append("\nLastName:"+empLName.getText()); status.append("\nType :"+types[selected]);

335  1992-2007 Pearson Education, Inc. All rights reserved. 335 switch(selected) { case 0: x=Double.parseDouble(empCommision.getText ()); status.append("\nCom Rate:“ +String.format("%10.2f",x)); x=Double.parseDouble(empSales.getText(); status.append("\nSalary:"+String.format(" %10.2f",x)); break;

336  1992-2007 Pearson Education, Inc. All rights reserved. 336 case 1: x=Double.parseDouble(empHours.getText()); status.append("\nHourly Rate:"+String.format("%10.2f",x)); break; case 2: x=Double.parseDouble(empWage.getText()); status.append("\nwage:"+String.format("%10.2f",x) ); break; } // end switch } // end if

337  1992-2007 Pearson Education, Inc. All rights reserved. 337 if(e.getSource() == cancel) { empName.setText(""); empLName.setText(""); status.setText(""); empCommision.setText(""); empSales.setText(""); empWage.setText(""); empHours.setText(""); } // end if

338  1992-2007 Pearson Education, Inc. All rights reserved. 338 if(e.getSource() == empType) { selected = empType.getSelectedIndex(); empCommision.setText(""); empSales.setText(""); empWage.setText(""); empHours.setText(""); for(j=0;j< typePanels.length;j++) if(j==selected) typePanels[j].setVisible(true); else typePanels[j].setVisible(false); } // end if getSource } // end method actionPerformed } // end inner class ButtonHandler } // end outer class


Download ppt " 1992-2007 Pearson Education, Inc. All rights reserved. 1 1212 1212 GUI Components: Part 1."

Similar presentations


Ads by Google