<<

UCLA PIC 20A Chapter 10 – GUIs Java Programming • JLabel • Event Handling Model • JTextField and JPasswordField • How Event Handling Works zInstructor: Ivo Dinov, • JButton Asst. Prof. In Statistics, Neurology and • JCheckBox and JRadioButton • JComboBox Program in Computing • JList • Multiple-Selection Lists • Mouse Event Handling zTeaching Assistant: Yon Seo Kim, PIC • Adapter Classes • Keyboard Event Handling • Layout Managers University of California, Los Angeles, Summer 2002 1. FlowLayout 2. BorderLayout http://www.stat.ucla.edu/~dinov/ 3. GridLayout

PIC 20A, UCLA, Ivo Dinov Slide 1 Slide 2 PIC 20A, UCLA, Ivo Dinov

Introduction Introduction z Graphical ("Goo-ee") z Example GUI: Netscape Communicator Text „ Pictorial interface to a program bar Menu field YDistinctive "look" and "feel" „ Different applications with consistent GUIs improve productivity http://www.stat.ucla.edu/~dinov/courses_students.html z GUIs built from components „ Component: object with which user interacts „ Examples: Labels, Text fields, Buttons, PIC 20A

Slide 3 PIC 20A, UCLA, Ivo Dinov Slide 4 PIC 20A, UCLA, Ivo Dinov

Swing Overview Overview

z Swing GUI components z Swing component inheritance hierarchy „ Defined in package javax.swing java.lang.Object

„ Original GUI components from Abstract Windowing java.awt.Component Toolkit in java.awt java.awt.Container YHeavyweight components - rely on local platform's windowing system for look and feel javax.swing.JComponent „ Swing components are lightweight YWritten in Java, not weighed down by complex GUI YComponent defines methods that can be used in its subclasses (for capabilities of platform example, paint and repaint) Y More portable than heavyweight components YContainer - collection of related components „ Swing components allow programmer to specify look V When using JFrames, attach components to the content pane (a and feel Container) V YCan change depending on platform Method add YJComponent YCan be same across all platforms - superclass to most Swing components YMuch of a component's functionality inherited from these classes

Slide 5 PIC 20A, UCLA, Ivo Dinov Slide 6 PIC 20A, UCLA, Ivo Dinov

1 JLabel Swing Overview z Labels z Some capabilities of subclasses of JComponent T Provide text instructions on a GUI „ T Read-only text T „ Shortcut keys (mnemonics) Programs rarely change a label's contents T Class JLabel (subclass of JComponent) YDirect access to components through keyboard http://www.stat.ucla.edu/~dinov/courses_students.html „ Common event handling Y If several components perform same actions z Methods „ Tool tips 18 label1 = new JLabel( "Label with text" ); YDescription of component that appears when mouse over it YCan declare label text in constructor T myLabel.setToolTipText( "Text" ) YDisplays "Text"in a tool tip when mouse over label T myLabel.setText( "Text" ) T myLabel.getText()

Slide 7 PIC 20A, UCLA, Ivo Dinov Slide 8 PIC 20A, UCLA, Ivo Dinov

JLabel JLabel

z z Alignment „ Object that implements interface Icon „ By default, text appears to right of image „ JLabel methods setHorizontalTextPosition and setVerticalTextPosition „ One class is ImageIcon (.gif and .jpeg images) YSpecify where text appears in label YUse integer constants defined in interface SwingConstants 24 Icon bug = new ImageIcon( "bug1.gif" ); (javax.swing) YAssumed same directory as program (more Chapter 16) VSwingConstants.LEFT, RIGHT, BOTTOM, CENTER „ Display an icon with setIcon method (of class JLabel) z Another JLabel constructor 33 label3.setIcon( bug ); YmyLabel.setIcon( myIcon ); T JLabel( "Text", ImageIcon, YmyLabel.getIcon //returns current Icon Text_Alignment_CONSTANT)

Slide 9 PIC 20A, UCLA, Ivo Dinov Slide 10 PIC 20A, UCLA, Ivo Dinov

1 // Fig. 12.4: LabelTest.java 31 label3 = new JLabel(); 2 // Demonstrating the JLabel class. z1. import 32 label3.setText( "Label with icon and text at bottom" ); 3 import javax.swing.*; z 33 label3.setIcon( bug ); 4 import java.awt.*; 1.1 Class Labeltest (extends JFrame) 34 label3.setHorizontalTextPosition( Use a no-argument constructor. Set 5 import java.awt.event.*; z 35 SwingConstants.CENTER ); text, icon, and alignment using 6 1.2 Declarations 36 label3.setVerticalTextPosition( methods. 7 public class LabelTest extends JFrame { z1.3 getContentPane 37 SwingConstants.BOTTOM ); 8 private JLabel label1, label2, label3; 38 label3.setToolTipText( "This is label3" ); 9 z2. Initialize JLabels 39 c.add( label3 ); 10 public LabelTest() 40 11 { z2.1 setToolTipText 41 setSize( 275, 170 ); 12 super( "Testing JLabel" ); 42 show(); 13 Create a Container object, to which we attach 43 } 14 Container c = getContentPane(); JLabel objects (subclass of JComponent). 44 15 c.setLayout( new FlowLayout() ); 45 public static void main( String args[] ) 16 46 { 17 // JLabel constructor with a string argument Initialize text in JLabel constructor. 47 LabelTest app = new LabelTest(); 18 label1 = new JLabel( "Label with text" ); 48 19 label1.setToolTipText( "This is label1" ); Set the tool tip text, and attach 49 app.addWindowListener( 20 c.add( label1 ); component to Container c. 50 new WindowAdapter() { 21 Create a new ImageIcon (assumed to be 51 public void windowClosing( WindowEvent e ) 22 // JLabel constructor with string, Icon and in same directory as program). More 52 { 23 // alignment arguments 53 System.exit( 0 ); 24 Icon bug = new ImageIcon( "bug1.gif" ); Chapter 16. 54 } z 25 label2 = new JLabel( "Label with text and icon", 2.2 setHorizontalText Position 55 } 26 bug, SwingConstants.LEFT ); z setVerticalText Position 56 ); 2.3 27 label2.setToolTipText( "This is label2" ); 57 } z2.3 setToolTipText 28 c.add( label2 ); ImageIcon 58 } z 29 Set and alignment 3. main 30 // JLabel constructor no arguments of text in JLabel constructor. PIC 20A, UCLA, Ivo Dinov Slide 11 PIC 20A, UCLA, Ivo Dinov Slide 12

2 Event Handling Model

z GUIs are event driven T Generate events when user interacts with GUI ‰Mouse movements, mouse clicks, typing in a text field, etc. T Event information stored in object that extends AWTEvent z To process an event zProgram Output T Register an event listener ‰Object from a class that implements an event-listener interface (from java.awt.event or javax.swing.event) ‰"Listens" for events T Implement event handler ‰Method called in response to event ‰Event handling interface has one or more methods that must be defined

PIC 20A, UCLA, Ivo Dinov Slide 13 Slide 14 PIC 20A, UCLA, Ivo Dinov

Event Handling Model JTextField and JPasswordField

z Delegation event model z JTextFieldsandJPasswordFields T Use of event listeners in event handling T Single line areas in which text can be entered or displayed T Processing of event delegated to particular object T JPasswordFields show inputted text as an asterisk * z When an event occurs T JTextField extends JTextComponent T GUI component notifies its listeners ‰JPasswordField extends JTextField ‰Calls listener's event handling method z When Enter pressed z Example: T ActionEvent occurs T Enter pressed in a JTextField T Currently active field "has the focus" T Method actionPerformed called for registered listener T Details in following sections

Slide 15 PIC 20A, UCLA, Ivo Dinov Slide 16 PIC 20A, UCLA, Ivo Dinov

JTextField and JPasswordField JTextField and JPasswordField z Methods z Class ActionEvent T Constructors T ‰JTextField( 10 ) Method getActionCommand VTextfield with 10 columns of text ‰Returns text in JTextField that generated event VTakes average character width, multiplies by 10 T Method getSource ‰JTextField( "Hi" ) ‰getSource returns Component reference VSets text, width determined automatically ‰JTextField( "Hi", 20 ) z Example T setEditable( boolean ) T Create JTextFields and a JPasswordField ‰If false, user cannot edit text ‰Can still generate events T Create and register an event handler T getPassword ‰Use getSource to determine which component had event ‰Class JPasswordField ‰Display a when Enter pressed ‰Returns password as an array of type char

Slide 17 PIC 20A, UCLA, Ivo Dinov Slide 18 PIC 20A, UCLA, Ivo Dinov

3 1 // Fig. 12.7: TextFieldTest.java 31 2 // Demonstrating the JTextField class. z 32 // construct textfield with default text 3 import java.awt.*; 1. import 33 password = new JPasswordField( "Hidden text" ); 4 import java.awt.event.*; z1.1 Declarations 34 c.add( password ); 5 import javax.swing.*; 35 JPasswordField initialized with 6 z1.2 Constructor 36 TextFieldHandler handler = new TextFieldHandler(); 7 public class TextFieldTest extends JFrame { z 37 text1.addActionListener( handler ); text, which appears as asterisks. 8 private JTextField text1, text2, text3; 1.3 GUI components 38 text2.addActionListener( handler ); 9 private JPasswordField password; z 39 text3.addActionListener( handler ); 10 2. Initialize text fields 40 password.addActionListener( handler ); 11 public TextFieldTest() z2.1 setEditable 41 12 { 42 setSize( 325, 100 ); Register event handlers. Good 13 super( "Testing JTextField and JPasswordField" ); 43 show(); practice to use an inner class as an 14 44 } event handler. 15 Container c = getContentPane(); 45 16 c.setLayout( new FlowLayout() ); Create new JTextField 46 public static void main( String args[] ) 17 objects using the various 47 { 18 // construct textfield with default sizing 48 TextFieldTest app = new TextFieldTest(); 19 text1 = new JTextField( 10 ); constructors. 49 20 c.add( text1 ); 50 app.addWindowListener( 21 51 new WindowAdapter() { 22 // construct textfield with default text 52 public void windowClosing( WindowEvent e ) 23 text2 = new JTextField( "Enter text here" );This text field cannot be modified (has 53 { 24 c.add( text2 ); a gray background). It can still 54 System.exit( 0 ); z2.2 JPasswordField 25 generate events. 55 } 26 // construct textfield with default text and 56 } 27 // 20 visible elements and no event handler 57 ); z2.3 Event handler 28 text3 = new JTextField( "Uneditable text field", 20 ); 58 } 29 text3.setEditable( false ); 59 z3. main 30 c.add( text3 ); 60 // inner class for event handling PIC 20A, UCLA, Ivo Dinov Slide 19 PIC 20A, UCLA, Ivo Dinov Slide 20

61 private class TextFieldHandler implements ActionListener { 62 public void actionPerformed( ActionEvent e ) zProgram Output 63 { 64 String s = ""; 65 66 if ( e.getSource() == text1 ) 67 s = "text1: " + e.getActionCommand(); 68 else if ( e.getSource() == text2 ) 69 s = "text2: " + e.getActionCommand(); Use getActionCommand to 70 else if ( e.getSource() == text3 ) get the text in the text field 71 s = "text3: " + e.getActionCommand(); that had the event. 72 else if ( e.getSource() == password ) { 73 JPasswordField pwd = 74 (JPasswordField) e.getSource(); 75 s = "password: " + 76 new String( pwd.getPassword()e.getSource() ); returns a Component 77 } reference, which is cast to a 78 JPasswordField. 79 JOptionPane.showMessageDialog( null, s ); 80 } z TextFieldHandler 81 } 4. Inner class (event handler) 82 } z4.1 getSource z4.2 getActionCommand z4.3 Downcast reference

PIC 20A, UCLA, Ivo Dinov Slide 21 PIC 20A, UCLA, Ivo Dinov Slide 22

How Event Handling Works JButton z Button z Registering event listeners T Component user clicks to trigger an action „ All JComponents contain an object of class T Several types of buttons EventListenerList called listenerList YCommand buttons, toggle buttons, check boxes, radio buttons „ When text1.addActionListener( handler ) z Command button executes T Generates ActionEvent when clicked Y New entry placed into listenerList T Created with class JButton z YInherits from class AbstractButton Handling events YDefines many features of Swing buttons „ When event occurs, has an event ID z JButton YComponent uses this to decide which method to call T Text on face called button label YIf ActionEvent, then actionPerformed called (in all T registered ActionListeners) Each button should have a different label T Can display Icons

Slide 23 PIC 20A, UCLA, Ivo Dinov Slide 24 PIC 20A, UCLA, Ivo Dinov

4 1 // ButtonTest.java z1. import 2 // Creating JButtons. JButton 3 import java.awt.*; z1.1 Declarations 4 import java.awt.event.*; 5 import javax.swing.*; z2. Initialize buttons and Icons z Methods of class JButton 6 7 public class ButtonTest extends JFrame {z2.1 setRolloverIcon „ Constructors 8 private JButton plainButton, fancyButton; 9 z2.2 Register event handler JButton myButton = new JButton( "Label" ); 10 public ButtonTest() 11 { JButton myButton = new JButton( "Label", 12 super( "Testing Buttons" ); 13 myIcon ); 14 Container c = getContentPane(); Create JButtons. Initialize fancyButton T 15 c.setLayout( new FlowLayout() );with an ImageIcon. setRolloverIcon( myIcon ) 16 Y 17 // create buttons Sets image to display when mouse over button 18 plainButton = new JButton( "Plain Button" ); 19 c.add( plainButton ); z Class ActionEvent 20 21 Icon bug1 = new ImageIcon( "bug1.gif" ); „ getActionCommand 22 Icon bug2 = new ImageIcon( "bug2.gif" ); 23 fancyButton = new JButton( "Fancy Button", bug1 ); YReturns label of button that generated event 24 fancyButton.setRolloverIcon( bug2 ); 25 c.add( fancyButton ); 26 Set a different icon to appear when the 27 // create an instance of inner class ButtonHandlermouse is over the JButton. 28 // to use for button event handling 29 ButtonHandler handler = new ButtonHandler(); 30 fancyButton.addActionListener( handler ); Slide 25 PIC 20A, UCLA, Ivo Dinov PIC 20A, UCLA, Ivo Dinov Slide 26

31 plainButton.addActionListener( handler ); 32 33 setSize( 275, 100 ); z z 34 show(); 3. main Program Output 35 } 36 z4. Inner class event handler 37 public static void main( String args[] ) 38 { 39 ButtonTest app = new ButtonTest(); 40 41 app.addWindowListener( 42 new WindowAdapter() { 43 public void windowClosing( WindowEvent e ) 44 { 45 System.exit( 0 ); 46 } 47 } 48 ); 49 } getActionCommand returns label of button 50 that generated event. 51 // inner class for button event handling 52 private class ButtonHandler implements ActionListener { 53 public void actionPerformed( ActionEvent e ) 54 { 55 JOptionPane.showMessageDialog( null, 56 "You pressed: " + e.getActionCommand() ); 57 } 58 } 59 } PIC 20A, UCLA, Ivo Dinov Slide 27 PIC 20A, UCLA, Ivo Dinov Slide 28

JCheckBox and JRadioButton JCheckBox and JRadioButton z State buttons z When JCheckBox changes „ JToggleButton „ ItemEvent generated YSubclasses JCheckBox, JRadioButton YHandled by an ItemListener, which must define „ Have on/off (true/false) values itemStateChanged „ Register handlers with with addItemListener z 51 private class CheckBoxHandler implements ItemListener { Class JCheckBox 55 public void itemStateChanged( ItemEvent e ) „ Text appears to right of 56 { „ Constructor JCheckBox myBox = new JCheckBox( "Title" z Class ItemEvent ); „ getStateChange YReturns ItemEvent.SELECTED or ItemEvent.DESELECTED

Slide 29 PIC 20A, UCLA, Ivo Dinov Slide 30 PIC 20A, UCLA, Ivo Dinov

5 1 // CheckBoxTest.java 2 // Creating Checkbox buttons. JCheckBox and JRadioButton 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 z z JTextField 7 public class CheckBoxTest extends JFrame { 1. import 8 private JTextField t; „ Method setText( fontObject ) 9 private JCheckBox bold, italic; z1.1 Declarations Y 10 new Font( name, style_CONSTANT, size ) 11 public CheckBoxTest() z Y 12 { 1.2 Initialize JCheckBoxes style_CONSTANT - FONT.PLAIN, BOLD, ITALIC 13 super( "JCheckBox Test" ); VCan add to get combinations 14 z 15 Container c = getContentPane(); 1.3 Register event handler 16 c.setLayout(new FlowLayout()); z Example 17 18 t = new JTextField( "Watch the font style change", 20 ); „ Use JCheckBoxes to change the font of a JTextField 19 t.setFont( new Font( "TimesRoman", Font.PLAIN, 14 ) ); 20 c.add( t ); 21 22 // create checkbox objects Create JCheckBoxes 23 bold = new JCheckBox( "Bold" ); 24 c.add( bold ); 25 26 italic = new JCheckBox( "Italic" ); 27 c.add( italic ); 28 29 CheckBoxHandler handler = new CheckBoxHandler(); 30 bold.addItemListener( handler ); Slide 31 PIC 20A, UCLA, Ivo Dinov PIC 20A, UCLA, Ivo Dinov Slide 32

31 italic.addItemListener( handler ); 32 62 33 addWindowListener( 63 if ( e.getSource() == italic ) 34 new WindowAdapter() { 64 if ( e.getStateChange() == ItemEvent.SELECTED ) 35 public void windowClosing( WindowEvent e ) 65 valItalic = Font.ITALIC; 36 { z2. main 66 else 37 System.exit( 0 ); 67 valItalic = Font.PLAIN; zProgram Output 38 } z 68 39 } 3. Inner class (event handler) 69 t.setFont( 40 ); 70 new Font( "TimesRoman", valBold + valItalic, 14 ) ); 41 z3.1 getStateChange 71 t.repaint(); 42 setSize( 275, 100 ); 72 } Use setFont to update the 43 show(); 73 } JTextField. 44 } Because CheckBoxHandler implements 74 } 45 46 public static void main( String args[]ItemListener ) , it must define method 47 { itemStateChanged 48 new CheckBoxTest(); 49 } 50 51 private class CheckBoxHandler implements ItemListenergetStateChange { returns 52 private int valBold = Font.PLAIN; ItemEvent.SELECTED 53 private int valItalic = Font.PLAIN; or 54 ItemEvent.DESELECTED 55 public void itemStateChanged( ItemEvent e ) 56 { 57 if ( e.getSource() == bold ) 58 if ( e.getStateChange() == ItemEvent.SELECTED ) 59 valBold = Font.BOLD; 60 else 61 valBold = Font.PLAIN;

PIC 20A, UCLA, Ivo Dinov Slide 33 PIC 20A, UCLA, Ivo Dinov Slide 34

JCheckBox and JRadioButton JCheckBox and JRadioButton

z Radio buttons z Class JRadioButton T Have two states: selected and deselected T Generates ItemEvents (like JCheckBox) T Normally appear as a group z Class ButtonGroup YOnly one in the group can be selected at time T ButtonGroup myGroup = new YSelecting one button forces the other buttons off ButtonGroup(); T Mutually exclusive options T T ButtonGroup - maintains logical relationship between Binds radio buttons into logical relationship T radio buttons Method add YAssociate a radio button with a group z Class JRadioButton myGroup.add( myRadioButton ) T Constructor YJRadioButton( "Label", selected ) YIf selected true, JRadioButton initially selected

Slide 35 PIC 20A, UCLA, Ivo Dinov Slide 36 PIC 20A, UCLA, Ivo Dinov

6 1 // RadioButtonTest.java 31 boldItalic = new JRadioButton( "Bold/Italic", false ); 2 // Creating radio buttons using ButtonGroup and JRadioButton. 32 c.add( boldItalic ); 3 import java.awt.*; 33 4 import java.awt.event.*; z 34 // register events 5 import javax.swing.*; 1. import 35 RadioButtonHandler handler = new RadioButtonHandler(); 6 36 plain.addItemListener( handler ); Create a ButtonGroup. Only 7 public class RadioButtonTest extends JFrame { z 37 bold.addItemListener( handler ); one radio button in the group may 8 private JTextField t; 1.1 Declarations 38 italic.addItemListener( handler ); be selected at a time. 9 private Font plainFont, boldFont, 39 boldItalic.addItemListener( handler ); 10 italicFont, boldItalicFont; z1.2 Initialization 40 11 private JRadioButton plain, bold, italic, boldItalic; 41 // create logical relationship between JRadioButtons 12 private ButtonGroup radioGroup; 42 radioGroup = new ButtonGroup(); 13 Method add adds radio 43 radioGroup.add( plain ); 14 public RadioButtonTest() 44 radioGroup.add( bold ); buttons to the ButtonGroup 15 { 45 radioGroup.add( italic ); 16 super( "RadioButton Test" ); 46 radioGroup.add( boldItalic ); 17 47 18 Container c = getContentPane(); 19 c.setLayout( new FlowLayout() ); 48 plainFont = new Font( "TimesRoman", Font.PLAIN, 14 ); 20 Initialize radio buttons. Only 49 boldFont = new Font( "TimesRoman", Font.BOLD, 14 ); 21 t = new JTextField( "Watch the font styleone change", is initially 25 selected. ); 50 italicFont = new Font( "TimesRoman", Font.ITALIC, 14 ); 22 c.add( t ); 51 boldItalicFont = 23 52 new Font( "TimesRoman", Font.BOLD + Font.ITALIC, 14 ); 24 // Create radio buttons 53 t.setFont( plainFont ); z2. Register event handler 25 plain = new JRadioButton( "Plain", true ); 54 26 c.add( plain ); 55 setSize( 300, 100 ); z2.1 ButtonGroup 27 bold = new JRadioButton( "Bold", false); 56 show(); 28 c.add( bold ); 57 } 29 italic = new JRadioButton( "Italic", false ); 58 z2.2 add 30 c.add( italic ); PIC 20A, UCLA, Ivo Dinov Slide 37 PIC 20A, UCLA, Ivo Dinov Slide 38

59 public static void main( String args[] ) 60 { 61 RadioButtonTest app = new RadioButtonTest(); 62 63 app.addWindowListener( 64 new WindowAdapter() { 65 public void windowClosing( WindowEvent e ) 66 { 67 System.exit( 0 ); 68 } z3. main 69 } 70 ); z 71 } 4. Inner class (event handler) Program Output 72 73 private class RadioButtonHandler implements ItemListener { 74 public void itemStateChanged( ItemEvent e ) 75 { 76 if ( e.getSource() == plain ) 77 t.setFont( plainFont ); 78 else if ( e.getSource() == bold ) 79 t.setFont( boldFont ); 80 else if ( e.getSource() == italic ) 81 t.setFont( italicFont ); 82 else if ( e.getSource() == boldItalic ) 83 t.setFont( boldItalicFont ); 84 85 t.repaint(); 86 } 87 } 88 } PIC 20A, UCLA, Ivo Dinov Slide 39 PIC 20A, UCLA, Ivo Dinov Slide 40

JComboBox JComboBox

z (drop down list) z JComboBox methods „ List of items, user makes a selection „ getSelectedIndex „ Class JComboBox YReturns the index of the currently selected item Y YGenerate ItemEvents myComboBox.getSelectedIndex() „ setMaximumRowCount( n ) z JComboBox YSet max number of elements to display when user clicks combo „ Constructor box JComboBox ( arrayOfNames ) YScrollbar automatically provided Y „ Numeric index keeps track of elements setMaximumRowCount( 3 ) YFirst element added at index 0 z Example Y First item added is appears as currently selected item when combo „ box appears Use JComboBox to set the Icon for a JLabel

Slide 41 PIC 20A, UCLA, Ivo Dinov Slide 42 PIC 20A, UCLA, Ivo Dinov

7 1 // Fig. 29.13: ComboBoxTest.java 31 public void itemStateChanged( ItemEvent e ) 2 // Using a JComboBox to select an image to display. 32 { 3 import java.awt.*; 33 label.setIcon( 4 import java.awt.event.*; z 34 icons[ images.getSelectedIndex() ] ); 5 import javax.swing.*; 1. import 35 } 6 z 36 } 7 public class ComboBoxTest extends JFrame { 1.1 Initialization 37 ); 38 8 private JComboBox images; z1.2 Constructor Use method getSelectedIndex 9 private JLabel label; 39 c.add( images ); Icon 10 private String names[] = z2. Initialize JComboBox 40 to determine which to use. 11 { "bug1.gif", "bug2.gif", z setMaximumRowCount 41 label = new JLabel( icons[ 0 ] ); 12 "travelbug.gif", "buganim.gif" }; 2.1 42 c.add( label ); 43 13 private Icon icons[] = z 2.2 Register 44 setSize( 350, 100 ); 14 { new ImageIcon( names[ 0 ] ), ItemListener 45 show(); 15 new ImageIcon( names[ 1 ] ), (anonymous 46 } 16 new ImageIcon( names[ 2 ] ), inner class) 47 17 new ImageIcon( names[ 3 ] ) }; 48 public static void main( String args[] ) 18 49 { 19 public ComboBoxTest() JComboBox 50 ComboBoxTest app = new ComboBoxTest(); 20 { Initialize with 51 21 super( "Testing JComboBox" ); an array of Strings. 52 app.addWindowListener( 22 53 new WindowAdapter() { 23 Container c = getContentPane(); 54 public void windowClosing( WindowEvent e ) 24 c.setLayout( new FlowLayout() ); 55 { 25 56 System.exit( 0 ); z 26 images = new JComboBox( names ); Set the number of rows to be 57 } 2.3 getSelectedIndex 27 images.setMaximumRowCount( 3 ); displayed at a time. 58 } 28 59 ); z main 29 images.addItemListener( 60 } 3. 30 new ItemListener() { 61 } PIC 20A, UCLA, Ivo Dinov Slide 43 PIC 20A, UCLA, Ivo Dinov Slide 44

JList JList

z List z JScrollPane object used for scrolling „ Displays series of items, may select one or more 40 c.add( new JScrollPane( colorList ) ); „ This section, discuss single-selection lists „ Takes component to which to add scrolling as argument „ z Class JList Add JScrollPane object to content pane „ Constructor JList( arrayOfNames ) z JList methods YTakes array of Objects (Strings) to display in list „ setSelectionMode( selection_CONSTANT ) „ setVisibleRowCount( n ) „ SINGLE_SELECTION YDisplays n items at a time YOne item selected at a time YDoes not provide automatic scrolling „ SINGLE_INTERVAL_SELECTION YMultiple selection list, allows contiguous items to be selected „ MULTIPLE_INTERVAL_SELECTION YMultiple-selection list, any items can be selected

Slide 45 PIC 20A, UCLA, Ivo Dinov Slide 46 PIC 20A, UCLA, Ivo Dinov

1 // ListTest.java 2 // Selecting colors from a JList. z1. import JList 3 import java.awt.*; 4 import java.awt.event.*; z1.1 Declarations 5 import javax.swing.*; 6 import javax.swing.event.*; z1.2 Initialize colorNames and z JList methods 7 colors 8 public class ListTest extends JFrame { „ getSelectedIndex() 9 private JList colorList; z1.3 Constructor 10 private Container c; YReturns index of selected item 11 12 private String colorNames[] = z 13 { "Black", "Blue", "Cyan", "Dark Gray", "Gray", "Green", Event handlers 14 "Light Gray", "Magenta", "Orange", "Pink", "Red", „ ListSelectionListener 15 "White", "Yellow" }; Implement interface 16 (javax.swing.event) 17 private Color colors[] = 18 { Color.black, Color.blue, Color.cyan, Color.darkGray, „ Define method valueChanged 19 Color.gray, Color.green, Color.lightGray, 20 Color.magenta, Color.orange, Color.pink, Color.red, „ Register handler with addListSelectionListener 21 Color.white, Color.yellow }; 22 z 23 public ListTest() Example 24 { 25 super( "List Test" ); „ Use a JList to select the background color 26 27 c = getContentPane(); 28 c.setLayout( new FlowLayout() ); 29 Slide 47 PIC 20A, UCLA, Ivo Dinov PIC 20A, UCLA, Ivo Dinov Slide 48

8 30 // create a list with the items in the colorNames array 60 31 colorList = new JList( colorNames ); Initialize JList with array of 61 app.addWindowListener( 32 colorList.setVisibleRowCount( 5 ); Strings, and show 5 items at 62 new WindowAdapter() { 33 63 public void windowClosing( WindowEvent e ) 34 // do not allow multiple selections a time. 35 colorList.setSelectionMode( 64 { 36 ListSelectionModel.SINGLE_SELECTION ); Make the JList a single- 65 System.exit( 0 ); 37 66 } selection list. 38 // add a JScrollPane containing the JList 67 } 39 // to the content pane 68 ); 40 c.add( new JScrollPane( colorList ) ); Create a new JScrollPane 69 } 41 object, initialize it with a JList, 42 // set up event handler 70 } 43 colorList.addListSelectionListener( and attach it to the content pane. 44 new ListSelectionListener() { 45 public void valueChanged( ListSelectionEventChange e ) the color according to the item zProgram Output 46 { selected (use getSelectedIndex). 47 c.setBackground( 48 colors[ colorList.getSelectedIndex() ] ); 49 } 50 } z2. Create JList 51 ); 52 z2.1 setVisibleRowCount 53 setSize( 350, 150 ); z setSelectionMode 54 show(); 2.2 55 } z2.3 JScrollPane 56 57 public static void main( String args[]z3. ) Event handler 58 { z 59 ListTest app = new ListTest(); 4. main PIC 20A, UCLA, Ivo Dinov Slide 49 PIC 20A, UCLA, Ivo Dinov Slide 50

Multiple-Selection Lists Multiple-Selection Lists

z Multiple selection lists z JList methods „ SINGLE_INTERVAL_SELECTION „ setFixedCellHeight( height ) YSelect a contiguous group of items by holding Shift key YSpecifies height in pixels of each item in JList „ MULTIPLE_INTERVAL_SELECTION „ setFixedCellWidth( width ) YSelect any amount of items YAs above, set width of list YHold Ctrl key and click each item to select z Example z JList methods „ Have two multiple-selection lists „ getSelectedValues() „ Copy button copies selected items in first list to other list YReturns an array of Objects representing selected items „ setListData( arrayOfObjects ) YSets items of JList to elements in arrayOfObjects

Slide 51 PIC 20A, UCLA, Ivo Dinov Slide 52 PIC 20A, UCLA, Ivo Dinov

z import 1 // MultipleSelection.java 1. 29 // create copy button 2 // Copying items from one List to another.z1.1 Initialize colorNames 30 copy = new JButton( "Copy >>>" ); 3 import javax.swing.*; z 31 copy.addActionListener( 4 import java.awt.*; 1.2 Initialize JList 32 new ActionListener() { 5 import java.awt.event.*; z 33 public void actionPerformed( ActionEvent e ) 6 1.3 setVisibleRowCount 34 { 7 public class MultipleSelection extends JFramez1.4 { setFixedCellHeight 35 // place selected values in copyList 8 private JList colorList, copyList; z 36 copyList.setListData( 9 private JButton copy; 1.5 setSelectionMode 37 colorList.getSelectedValues() ); 38 } 10 private String colorNames[] = z 1.6 JScrollPane 39 } 11 { "Black", "Blue", "Cyan", "Dark Gray", "Gray", 40 ); Use the array returned by 12 "Green", "Light Gray", "Magenta", "Orange", "Pink", 41 c.add( copy ); getSelectedValues to set 13 "Red", "White", "Yellow" }; 42 the items of copyList. 14 43 copyList = new JList( ); 15 public MultipleSelection() 44 copyList.setVisibleRowCount( 5 ); 16 { Initialize the JList with an 45 copyList.setFixedCellWidth( 100 ); 17 super( "Multiple Selection Lists" ); String array of s. 46 copyList.setFixedCellHeight( 15 ); 18 Specify the number of items 47 copyList.setSelectionMode( 19 Container c = getContentPane(); to appear at a time. 48 ListSelectionModel.SINGLE_INTERVAL_SELECTION ); 20 c.setLayout( new FlowLayout() ); 49 c.add( new JScrollPane( copyList ) ); 21 Set the cell height 50 22 colorList = new JList( colorNames ); z2. JButton Specify that list is to be 51 setSize( 300, 120 ); 23 colorList.setVisibleRowCount( 5 ); MULTIPLE_INTERVAL_SELECTION 52 show(); z2.1 Event handler (anonymous inner class) 24 colorList.setFixedCellHeight( 15 ); 53 } z 25 colorList.setSelectionMode( 2.2 setListData 54 26 ListSelectionModel.MULTIPLE_INTERVAL_SELECTION ); z2.2.1 getSelectedValues 27 c.add( new JScrollPane( colorList ) ); z 28 2.3 Initialize JList PIC 20A, UCLA, Ivo Dinov Slide 53 PIC 20A, UCLA, Ivo Dinov Slide 54

9 55 public static void main( String args[] ) 56 { 57 MultipleSelection app = new MultipleSelection(); Mouse Event Handling 58 59 app.addWindowListener( 60 new WindowAdapter() { 61 public void windowClosing( WindowEvent e ) z Mouse events 62 { 63 System.exit( 0 ); „ 64 } Can be trapped for any GUI component derived from 65 } java.awt.Component 66 ); 67 } „ Mouse event handling methods 68 } ‰Take a MouseEvent object VContains info about event, including x and y coordinates z3. main VMethods getX and getY „ z Interfaces MouseListener and Program Output MouseMotionListener ‰addMouseListener ‰addMouseMotionListener ‰Must define all methods

PIC 20A, UCLA, Ivo Dinov Slide 55 Slide 56 PIC 20A, UCLA, Ivo Dinov

Mouse Event Handling Mouse Event Handling

z Interface MouseListener z Interface MouseMotionListener T public void mousePressed( MouseEvent e ) T public void mouseDragged( MouseEvent e ) ‰Mouse pressed on a component ‰Mouse pressed and moved T public void mouseClicked( MouseEvent e ) T public void mouseMoved( MouseEvent e ) ‰Mouse pressed and released ‰Mouse moved when over component T public void mouseReleased( MouseEvent e ) 17 getContentPane().add( statusBar, BorderLayout.SOUTH ); ‰Mouse released T public void mouseEntered( MouseEvent e ) T Adds component statusBar to the bottom portion of the ‰Mouse enters bounds of component content pane T public void mouseExited( MouseEvent e ) ‰Mouse leaves bounds of component

Slide 57 PIC 20A, UCLA, Ivo Dinov Slide 58 PIC 20A, UCLA, Ivo Dinov

1 // MouseTracker.java 30 statusBar.setText( "Clicked at [" + e.getX() + 2 // Demonstrating mouse events. 31 ", " + e.getY() + "]" ); 3 Class implements interfaces MouseListener and 32 } 4 import java.awt.*; MouseMotionListener to listen for mouse 33 5 import java.awt.event.*; 34 public void mousePressed( MouseEvent e ) getX and getY return the coordinates 6 import javax.swing.*; events. There are seven methods to define. 35 { of where the mouse event occurred. 7 36 statusBar.setText( "Pressed at [" + e.getX() + 8 public class MouseTracker extends JFrame 37 ", " + e.getY() + "]" ); 9 implements MouseListener, MouseMotionListener { 38 } 10 private JLabel statusBar; Puts the JLabel component at the bottom 39 11 of the content pane. More later. 40 public void mouseReleased( MouseEvent e ) 12 public MouseTracker() 41 { 13 { 42 statusBar.setText( "Released at [" + e.getX() + 14 super( "Demonstrating Mouse Events" ); 43 ", " + e.getY() + "]" ); 15 44 } 16 statusBar = new JLabel(); 45 17 getContentPane().add( statusBar, BorderLayout.SOUTH ); 46 public void mouseEntered( MouseEvent e ) 18 47 { 19 // application listens to its own mouse events 48 statusBar.setText( "Mouse in " ); 20 addMouseListener( this ); Application is its own event handler 49 } z getX getY 50 2.1 and 21 addMouseMotionListener( this ); 51 public void mouseExited( MouseEvent e ) 22 52 { 23 setSize( 275, 100 ); z1. import 53 statusBar.setText( "Mouse outside window" ); 24 show(); 54 } 25 } z implements 1. Class MouseTracker ( 55 26 MouseListener, MouseMotion Listener) 56 // MouseMotionListener event handlers 27 // MouseListener event handlers 57 public void mouseDragged( MouseEvent e ) 28 public void mouseClicked( MouseEventz1.2 Register e ) event handlers (this) 58 { 29 { 59 statusBar.setText( "Dragged at [" + e.getX() + z2. Define event handler methods 60 ", " + e.getY() + "]" ); PIC 20A, UCLA, Ivo Dinov Slide 59 PIC 20A, UCLA, Ivo Dinov Slide 60

10 61 } 62 z3. main 63 public void mouseMoved( MouseEvent e ) 64 { 65 statusBar.setText( "Moved at [" + e.getX() + 66 ", " + e.getY() + "]" ); 67 } 68 69 public static void main( String args[] ) 70 { 71 MouseTracker app = new MouseTracker(); 72 73 app.addWindowListener( 74 new WindowAdapter() { 75 public void windowClosing( WindowEvent e ) 76 { 77 System.exit( 0 ); z 78 } Program Output 79 } 80 ); 81 } 82 }

PIC 20A, UCLA, Ivo Dinov Slide 61 PIC 20A, UCLA, Ivo Dinov Slide 62

Adapter Classes Adapter Classes

z Time consuming to define all interface methods z Adapter classes T MouseListener and MouseMotionListener have seven methods ComponentAdapter ComponentListener YWhat if we only want to use one? ContainerAdapter ContainerListener YRequired to define all methods in interface FocusAdapter FocusListener KeyAdapter KeyListener z Adapter class MouseAdapter MouseListener T Implements an interface MouseMotionAdapter MouseMotionListener YDefault implementation (empty body) for all methods WindowAdapter WindowListener T Programmer extends adapter class YOverrides methods he wants to use T Has "is a" relationship with interface YMouseAdapter is a MouseListener

Slide 63 PIC 20A, UCLA, Ivo Dinov Slide 64 PIC 20A, UCLA, Ivo Dinov

Adapter Classes Adapter Classes

18 addMouseMotionListener( 40 Painter app = new Painter(); 19 new MouseMotionAdapter() { 42 app.addWindowListener( 20 public void mouseDragged( MouseEvent e ) 43 new WindowAdapter() { 21 { 44 public void windowClosing( WindowEvent e ) 45 { T Anonymous inner class 46 System.exit( 0 ); 47 } Y Extends MouseMotionAdapter (which implements 48 } MouseMotionListener) 49 ); Y Inner class gets default (empty body) implementation of T Used in applications extending JFrame mouseMoved and mouseDragged T Interface WindowListener specifies seven methods YOverride methods want to use YWindowAdapter define these for us T Only override the method we want YwindowClosing YEnables use of close button

Slide 65 PIC 20A, UCLA, Ivo Dinov Slide 66 PIC 20A, UCLA, Ivo Dinov

11 1 // Painter.java 2 // Using class MouseMotionAdapter. 3 import javax.swing.*; z Adapter Classes 4 import java.awt.event.*; 1. import 5 import java.awt.*; 6 z1.1 addMouseMotion Listener z Example program 7 public class Painter extends JFrame { 8 private int xValue = -10,1.2. yValue MouseMotionAdapter = -10; T 9 Simple paint program 10 public Painter() T 11 { Draw oval whenever user drags mouse 12 super( "A simple paint program" ); T Only want to define method mouseDragged 13 Use adapter class so we do not have to define all the 14 getContentPane().add( methods of interface MouseMotionListner. Y MouseMotionAdapter 15 new Label( "Drag the mouse to draw" ), Use 16 BorderLayout.SOUTH ); 17 18 addMouseMotionListener( 19 new MouseMotionAdapter() { 20 public void mouseDragged( MouseEvent e ) 21 { 22 xValue = e.getX(); 23 yValue = e.getY(); Update xValue and yValue, 24 repaint(); then call repaint. 25 } 26 } 27 ); 28 29 setSize( 300, 150 ); 30 show(); 31 } Slide 67 PIC 20A, UCLA, Ivo Dinov PIC 20A, UCLA, Ivo Dinov Slide 68

32 33 public void paint( Graphics g ) 34 { Adapter Classes 35 g.fillOval( xValue, yValue, 4, 4 ); Draw an oval based at location 36 } xValue, yValue. 37 z Class MouseEvent 38 public static void main( String args[] ) 39 { T Inherits from InputEvent 40 Painter app = new Painter(); 41 T Can distinguish between buttons on multi-button mouse 42 app.addWindowListener( 43 new WindowAdapter() { YCombination of a mouse click and a keystroke 44 public void windowClosing( WindowEvent e ) T 45 { Java assumes every mouse has a left mouse button 46 System.exit( 0 ); YAlt + click = center mouse button 47 } 48 } YMeta + click = right mouse button 49 ); T Method getClickCount 50 } z2. paint 51 } YReturns number of mouse clicks (separate for each button) z3. main T Methods isAltDown and isMetaDown z3.1 addWindowListener YReturns true if Alt or Meta key down when mouse clicked z3.2 WindowAdapter

PIC 20A, UCLA, Ivo Dinov Slide 69 Slide 70 PIC 20A, UCLA, Ivo Dinov

1 // MouseDetails.java 2 // Demonstrating mouse clicks and Adapter Classes 3 // distinguishing between mouse buttons. 4 import javax.swing.*; 5 import java.awt.*; z z 6 import java.awt.event.*; 1. import Class JFrame 7 T setTitle( "String" ) 8 public class MouseDetails extends JFrame { z Method 9 private String s = ""; 1.1 Constructor YSets title bar of window 10 private int xPos, yPos; 11 z1.2 Register event handler PIC 20A Spring 2002 – Home Page Prof. I.D. Dinov 12 public MouseDetails() 13 { z2. paint 14 super( "Mouse clicks and buttons" ); 15 16 addMouseListener( new MouseClickHandler() ); 17 18 setSize( 350, 150 ); 19 show(); 20 } 21 22 public void paint( Graphics g ) 23 { 24 g.drawString( "Clicked @ [" + xPos + ", " + yPos + "]", 25 xPos, yPos ); 26 } 27

Slide 71 PIC 20A, UCLA, Ivo Dinov PIC 20A, UCLA, Ivo Dinov Slide 72

12 28 public static void main( String args[] ) 29 { 59 setTitle( s ); // set the title bar of the window 30 MouseDetails app = new MouseDetails(); 60 repaint(); 31 61 } 32 app.addWindowListener( 62 } Set the title bar. 33 new WindowAdapter() { 63 } 34 public void windowClosing( WindowEvent e ) 35 { 36 System.exit( 0 ); Use a named inner class as the event handler. Can still z 37 } inherit from MouseAdapter (extends MouseAdapter). 4.4 setTitle 38 } 39 ); z 40 } Program Output 41 42 // inner class to handle mouse events 43 private class MouseClickHandler extends MouseAdapter { 44 public void mouseClicked( MouseEvent e ) 45 { Use getClickCount, isAltDown, 46 xPos = e.getX(); and isMetaDown to determine the 47 yPos = e.getY(); String to use. 48 49 String s = 50 "Clicked " + e.getClickCount() + " time(s)"; 51 z3. main 52 if ( e.isMetaDown() ) // Right mouse button 53 s += " with right mouse button"; z4. Inner class (event handler) 54 else if ( e.isAltDown() ) // Middle mousez button 55 s += " with center mouse button"; 4.1 getClickCount 56 else // Left mousez button4.2 isMetaDown 57 s += " with left mouse button"; z 58 4.3 isAltDown PIC 20A, UCLA, Ivo Dinov Slide 73 PIC 20A, UCLA, Ivo Dinov Slide 74

Keyboard Event Handling Keyboard Event Handling

z Interface KeyListener z KeyEvent methods „ Handles key events (keys pressed on keyboard) „ getKeyCode „ Must define methods ‰Every key represented with a virtual key code (constant) ‰keyPressed - called when any key pressed ‰Complete list in on-line documentation (java.awt.event) ‰keyTyped - called when non-action key pressed „ getKeyText VAction keys: arrow keys, home, end, page up, page down, function ‰Takes key code constant, returns name of key keys, num lock, print screen, scroll lock, caps lock, pause „ getKeyChar ‰keyReleased - called for any key after it is released ‰Gets Unicode character of key pressed ‰Each get a KeyEvent as an argument „ VSubclass of InputEvent isActionKey ‰Returns true if key that generated event is an action key

Slide 75 PIC 20A, UCLA, Ivo Dinov Slide 76 PIC 20A, UCLA, Ivo Dinov

1 // KeyDemo.java 2 // Demonstrating keystroke events. Keyboard Event Handling 3 import javax.swing.*; 4 import java.awt.*; 5 import java.awt.event.*; z 6 KeyEvent methods 7 public class KeyDemo extends JFrame implements KeyListener { 8 private String line1 = "", line2 = ""; „ getModifiers (from class InputEvent) 9 private String line3 = ""; ‰ 10 private JTextArea textArea; Class implements interface KeyListener, so it Returns which modifiers were pressed 11 must define the three required methods. „ getKeyModifierText ( e.getModifiers ) 12 public KeyDemo() 13 { ‰Returns string containing names of modifier keys 14 super( "Demonstrating Keystroke Events" ); 15 16 textArea = new JTextArea( 10, 15 ); z Upcoming example 17 textArea.setText( "Press any key on the keyboard..." ); 18 textArea.setEnabled( false ); „ Create a JTextArea 19 20 // allow to process Key events „ Modify text depending on what keys are pressed 21 addKeyListener( this ); Register the event handler. 22 23 getContentPane().add( textArea ); 24 z 25 setSize( 350, 100 ); 1. import 26 show(); z1.1 Class KeyDemo (implements KeyListener) 27 } 28 z1.2 addKeyListener

Slide 77 PIC 20A, UCLA, Ivo Dinov PIC 20A, UCLA, Ivo Dinov Slide 78

13 29 public void keyPressed( KeyEvent e ) 30 { 31 line1 = "Key pressed: " + 32 e.getKeyText( e.getKeyCode() ); 33 setLines2and3( e ); 61 textArea.setText( 34 } getKeyCode returns the virtual key code. 62 line1 + "\n" + line2 + "\n" + line3 + "\n" ); z 35 getKeyText converts the key code to a 3. main 63 } 36 public void keyReleased( KeyEventString e ) containing the name. 37 { 64 38 line1 = "Key released: " + 65 public static void main( String args[] ) 39 e.getKeyText( e.getKeyCode() ); z2. Event handling methods 66 { 40 setLines2and3( e ); z 41 } 2.1 getKeyText 67 KeyDemo app = new KeyDemo(); 42 z 2.2 getKeyCode 68 43 public void keyTyped( KeyEvent e ) z 44 { 2.3 isActionKey 69 app.addWindowListener( z 45 line1 = "Key typed: " + e.getKeyChar(); 2.4 Determine modifier keys 70 new WindowAdapter() { 46 setLines2and3( e ); 47 } 71 public void windowClosing( WindowEvent e ) 48 72 { 49 private void setLines2and3( KeyEvent e ) Test if the key is 73 System.exit( 0 ); 50 { an action key 51 line2 = "This key is " + 74 } 52 ( e.isActionKey() ? "" : "not " ) + 75 } 53 "an action key"; getModifiers returns the 76 ); 54 modifier keys, and 55 String temp = getKeyModifersText 77 } 56 e.getKeyModifiersText( e.getModifiers() ); 78 } 57 turns them into a String. 58 line3 = "Modifier keys pressed: " + 59 ( temp.equals( "" ) ? "none" : temp ); 60 PIC 20A, UCLA, Ivo Dinov Slide 79 PIC 20A, UCLA, Ivo Dinov Slide 80

zProgram Output Layout Managers

z Layout managers „ Arrange GUI components on a container „ Provide basic layout capabilities ‰Easier to use than determining exact size and position of every component ‰Programmer concentrates on "look and feel" rather than details

PIC 20A, UCLA, Ivo Dinov Slide 81 Slide 82 PIC 20A, UCLA, Ivo Dinov

1 // FlowLayoutDemo.java z 2 // Demonstrating FlowLayout alignments. 1. import FlowLayout 3 import java.awt.*; z1.1 Declarations 4 import java.awt.event.*; 5 import javax.swing.*; z1.2 Initialize FlowLayout 6 z1.3 Create button z Most basic 7 public class FlowLayoutDemo extends JFrame { 8 private JButton left, center, right; z1.4 Event handler „ Components placed left to right in order added 9 private Container c; z 10 private FlowLayout layout; 1.4.1 setAlignment „ 11 z1.4.2 layoutContainer When edge of container reached, continues on next line 12 public FlowLayoutDemo() „ Components can be left-aligned, centered (default), or 13 { 14 super( "FlowLayout Demo" ); setAlignment changes the right-aligned 15 16 layout = new FlowLayout(); alignment of the layout. 17 z 18 c = getContentPane(); FlowLayout methods Use method layoutContainer to 19 c.setLayout( layout ); „ setAlignment( position_CONSTANT ) 20 update changes 21 left = new JButton( "Left" ); ‰FlowLayout.LEFT, FlowLayout.CENTER, 22 left.addActionListener( 23 new ActionListener() { FlowLayout.RIGHT 24 public void actionPerformed( ActionEvent e ) „ layoutContainer( container ) 25 { 26 layout.setAlignment( FlowLayout.LEFT ); ‰Update Container specified with layout 27 V 28 // re-align attached components I.e., content pane 29 layout.layoutContainer( c ); 30 } Slide 83 PIC 20A, UCLA, Ivo Dinov PIC 20A, UCLA, Ivo Dinov Slide 84

14 31 } 61 c.add( right ); 32 ); 62 33 c.add( left ); 63 setSize( 300, 75 ); 34 64 show(); 35 center = new JButton( "Center" ); 65 } 36 center.addActionListener( 66 37 new ActionListener() { 67 public static void main( String args[] ) z main 38 public void actionPerformed( ActionEvent e ) 68 { 4. 39 { z1.5 add JButton 69 FlowLayoutDemo app = new FlowLayoutDemo(); 40 layout.setAlignment( FlowLayout.CENTER ); 70 zProgram Output 41 z 71 app.addWindowListener( 42 // re-align attached components 2. JButton 72 new WindowAdapter() { 43 layout.layoutContainer( c ); 73 public void windowClosing( WindowEvent e ) 44 } z2.1 Event handler 74 { 45 } 75 System.exit( 0 ); 46 ); 76 } 47 c.add( center ); z3. JButton 77 } 48 78 ); 49 right = new JButton( "Right" ); z 79 } 50 right.addActionListener( 3.1 Event handler 80 } 51 new ActionListener() { 52 public void actionPerformed( ActionEvent e ) 53 { 54 layout.setAlignment( FlowLayout.RIGHT ); 55 56 // re-align attached components 57 layout.layoutContainer( c ); 58 } 59 } 60 ); PIC 20A, UCLA, Ivo Dinov Slide 85 PIC 20A, UCLA, Ivo Dinov Slide 86

BorderLayout BorderLayout z z BorderLayout Methods „ Constructor: BorderLayout( hGap, vGap ); „ Default manager for content pane YhGap - horizontal gap space between regions „ Arrange components into 5 regions YvGap - vertical gap space between regions YNorth, south, east, west, center YDefault is 0 for both „ Up to 5 components can be added directly „ Adding components YOne for each region YmyContainer.add( component, position ) „ Components placed in Ycomponent - component to add YNorth/South - Region is as tall as component Yposition - BorderLayout.NORTH YEast/West - Region is as wide as component VSOUTH, EAST, WEST, CENTER similar YCenter - Region expands to take all remaining space

Slide 87 PIC 20A, UCLA, Ivo Dinov Slide 88 PIC 20A, UCLA, Ivo Dinov

1 // BorderLayoutDemo.java 2 // Demonstrating BorderLayout. BorderLayout 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 z Methods 7 public class BorderLayoutDemo extends JFrame 8 implements ActionListener { „ setVisible( boolean ) ( in class JButton) 9 private JButton b[]; 10 private String names[] = YIf false, hides component 11 { "Hide North", "Hide South", "Hide East", „ 12 "Hide West", "Hide Center" }; layoutContainer( container ) - updates 13 private BorderLayout layout; 14 Set horizontal and vertical container, as before 15 public BorderLayoutDemo() spacing in constructor. 16 { 17 super( "BorderLayout Demo" ); 18 19 layout = new BorderLayout( 5, 5 ); 20 z1. import 21 Container c = getContentPane(); 22 c.setLayout( layout ); z1.1 Declarations 23 24 // instantiate button objects z1.2 Initialize layout 25 b = new JButton[ names.length ]; z 26 1.3 Create JButtons 27 for ( int i = 0; i < names.length; i++ ) { z1.4 Register event handler 28 b[ i ] = new JButton( names[ i ] ); 29 b[ i ].addActionListener( this ); 30 } Slide 89 PIC 20A, UCLA, Ivo Dinov PIC 20A, UCLA, Ivo Dinov Slide 90

15 31 61 public void windowClosing( WindowEvent e ) 32 // order not important 33 c.add( b[ 0 ], BorderLayout.NORTH ); // North position 62 { 34 c.add( b[ 1 ], BorderLayout.SOUTH ); // South position 63 System.exit( 0 ); 35 c.add( b[ 2 ], BorderLayout.EAST ); // East position 64 } 36 c.add( b[ 3 ], BorderLayout.WEST ); // West position 65 } z 37 c.add( b[ 4 ], BorderLayout.CENTER ); // Center position 66 ); Program Output 38 67 } 39 setSize( 300, 200 ); 40 show(); 68 } 41 } 42 43 public void actionPerformed( ActionEvent e ) 44 { Hide the button that 45 for ( int i = 0; i < b.length; i++ ) generated the event. 46 if ( e.getSource() == b[ i ] ) 47 b[ i ].setVisible( false ); 48 else 49 b[ i ].setVisible( true ); Recalculates layout of content 50 pane. 51 // re-layout the content pane 52 layout.layoutContainer( getContentPane() ); z 53 } 2. add (specify position) 54 z 55 public static void main( String args[] ) 3. actionPerformed 56 { z3.1 setVisible 57 BorderLayoutDemo app = new BorderLayoutDemo(); 58 z3.2 layoutContainer 59 app.addWindowListener( z 60 new WindowAdapter() { 4. main PIC 20A, UCLA, Ivo Dinov Slide 91 PIC 20A, UCLA, Ivo Dinov Slide 92

zProgram Output GridLayout

z GridLayout „ Divides container into a grid „ Components placed in rows and columns „ All components have same width and height YAdded starting from top left, then from left to right YWhen row full, continues on next row, left to right z Constructors „ GridLayout( rows, columns, hGap, vGap ) YSpecify number of rows and columns, and horizontal and vertical gaps between elements (in pixels) „ GridLayout( rows, columns ) YDefault 0 for hGap and vGap

PIC 20A, UCLA, Ivo Dinov Slide 93 Slide 94 PIC 20A, UCLA, Ivo Dinov

1 // GridLayoutDemo.java 2 // Demonstrating GridLayout. GridLayout 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class GridLayoutDemo extends JFrame z Updating containers 8 implements ActionListener { „ 9 private JButton b[]; Container method validate 10 private String names[] = YRe-layouts a container for which the layout has changed 11 { "one", "two", "three", "four", "five", "six" }; 12 private boolean toggle = true; „ 13 private Container c; Example: 14 private GridLayout grid1, grid2; Container c = getContentPane; 15 Create two GridLayouts, 16 public GridLayoutDemo() a 2 by 3 and a 3 by 2 (rows, c.setLayout( myLayout ); 17 { columns). 18 super( "GridLayout Demo" ); if(x=3){ 19 c.setLayout( myLayout2 ); 20 grid1 = new GridLayout( 2, 3, 5, 5 ); 21 grid2 = new GridLayout( 3, 2 ); z c.validate(); 22 1. import 23 c = getContentPane(); } 24 c.setLayout( grid1 ); z1.1 Declarations Y c 25 Changes layout and updates if condition met 26 // create and add buttons z1.2 Initialize layout 27 b = new JButton[ names.length ]; 28 z 29 for (int i = 0; i < names.length; i++ ) { 1.3 Register event handler 30 b[ i ] = new JButton( names[ i ] ); 31 b[ i ].addActionListener( this ); Slide 95 PIC 20A, UCLA, Ivo Dinov PIC 20A, UCLA, Ivo Dinov Slide 96

16 32 c.add( b[ i ] ); 33 } Add buttons to layout. 34 35 setSize( 300, 150 ); Added from left to right in zProgram Output 36 show(); order. 37 } 38 39 public void actionPerformed( ActionEvent e ) 40 { 41 if ( toggle ) Toggle layouts and 42 c.setLayout( grid2 ); update content pane 43 else validate 44 c.setLayout( grid1 ); with . 45 46 toggle = !toggle; 47 c.validate(); z1.4 add 48 } 49 50 public static void main( String args[] ) z2. actionPerformed 51 { 52 GridLayoutDemo app = new GridLayoutDemo();z 53 3. main 54 app.addWindowListener( 55 new WindowAdapter() { 56 public void windowClosing( WindowEvent e ) 57 { 58 System.exit( 0 ); 59 } 60 } 61 ); 62 } 63 } PIC 20A, UCLA, Ivo Dinov Slide 97 PIC 20A, UCLA, Ivo Dinov Slide 98

Panels Panels z Complex GUIs z Usage „ Each component needs to be placed in an exact location „ Create panels, and set the layout for each „ Can use multiple panels „ Add components to the panels as needed YEach panel's components arranged in a specific layout „ Add the panels to the content pane (default z Panels BorderLayout) „ Class JPanel inherits from JComponent, which inherits from java.awt.Container YEvery JPanel is a Container „ JPanels can have components (and other JPanels) added to them YJPanel sized to components it contains YGrows to accomodate components as they are added

Slide 99 PIC 20A, UCLA, Ivo Dinov Slide 100 PIC 20A, UCLA, Ivo Dinov

1 // PanelDemo.java 2 // Using a JPanel to help lay out components. 32 3 import java.awt.*; 33 public static void main( String args[] ) 4 import java.awt.event.*; z1. import 34 { 5 import javax.swing.*; 35 PanelDemo app = new PanelDemo(); 6 z1.1 Declarations 36 7 public class PanelDemo extends JFrame { z1.2 Initialize buttonPanel 37 app.addWindowListener( 8 private JPanel buttonPanel; 38 new WindowAdapter() { 9 private JButton buttons[]; z1.3 GridLayout 39 public void windowClosing( WindowEvent e ) 10 z1.4 ButtonPanel.add 40 { 11 public PanelDemo() 41 System.exit( 0 ); z2. main 12 { z1.5 c.add 42 } 13 super( "Panel Demo" ); 43 } z 14 44 ); Program Output 15 Container c = getContentPane(); 45 } 16 buttonPanel = new JPanel(); Create a new panel. 46 } 17 buttons = new JButton[ 5 ]; 18 19 buttonPanel.setLayout( 20 new GridLayout( 1, buttons.length ) ); 21 22 for ( int i = 0; i < buttons.length; i++ ) { 23 buttons[ i ] = new JButton( "Button " + (i + 1) ); 24 buttonPanel.add( buttons[ i ] ); 25 } Add components to panel. 26 JPanel sized to its 27 c.add( buttonPanel, BorderLayout.SOUTH ); components. Grows as 28 needed. 29 setSize( 425, 150 ); Add panel to the content pane 30 show(); (BorderLayout.SOUTH). 31 } PIC 20A, UCLA, Ivo Dinov Slide 101 PIC 20A, UCLA, Ivo Dinov Slide 102

17