UCLA PIC 20A Java Programming PIC 20A. Introduction. Introduction. Swing Overview. Swing Overview. Chapter 10 GUIs. Instructor: Ivo Dinov, Label

UCLA PIC 20A Java Programming zInstructor: Ivo Dinov, Asst. Prof. In Statistics, Neurology and Program in Computing zTeaching Assistant: Yon Seo Ki...
1 downloads 1 Views 770KB Size
UCLA PIC 20A Java Programming zInstructor:

Ivo Dinov,

Asst. Prof. In Statistics, Neurology and Program in Computing zTeaching

Assistant: Yon Seo Kim,

PIC

University of California, Los Angeles, Summer 2002

http://www.stat.ucla.edu/~dinov/ PIC 20A, UCLA, Ivo Dinov

Chapter 10 – GUIs • • • • • • • • • • • • •

JLabel Event Handling Model JTextField and JPasswordField How Event Handling Works JButton JCheckBox and JRadioButton JComboBox JList Multiple-Selection Lists Mouse Event Handling Adapter Classes Keyboard Event Handling Layout Managers

1. FlowLayout 2. BorderLayout 3. GridLayout

Slide 1

Slide 2

Introduction

PIC 20A, UCLA, Ivo Dinov

Introduction

z Graphical User Interface ("Goo-ee") „ Pictorial interface to a program

z Example GUI: Netscape Communicator Button

Label

Menu

Menu bar

YDistinctive "look" and "feel"

Text field

„ 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, Checkboxes

Slide 3

PIC 20A Slide 4

PIC 20A, UCLA, Ivo Dinov

Swing Overview z Swing GUI components

PIC 20A, UCLA, Ivo Dinov

Swing Overview z Swing component inheritance hierarchy

„ Defined in package javax.swing „ Original GUI components from Abstract Windowing Toolkit in java.awt YHeavyweight components - rely on local platform's windowing system for look and feel

java.lang.Object java.awt.Component java.awt.Container javax.swing.JComponent

„ Swing components are lightweight

YWritten in Java, not weighed down by complex GUI capabilities of platform YMore portable than heavyweight components

„ Swing components allow programmer to specify look and feel YCan change depending on platform YCan be same across all platforms Slide 5

Y Component defines methods that can be used in its subclasses (for example, paint and repaint) Y Container - collection of related components V When using JFrames, attach components to the content pane (a Container) V Method add

Y JComponent - superclass to most Swing components Y Much of a component's functionality inherited from these classes 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 T T T

„ Pluggable look and feel „ Shortcut keys (mnemonics) YDirect access to components through keyboard

Provide text instructions on a GUI Read-only text Programs rarely change a label's contents Class JLabel (subclass of JComponent) http://www.stat.ucla.edu/~dinov/courses_students.html

„ Common event handling YIf several components perform same actions

z Methods

„ Tool tips

18

YDescription of component that appears when mouse over it

label1 = new JLabel( "Label with text" );

Y Can declare label text in constructor

T myLabel.setToolTipText( "Text" ) Y Displays "Text"in a tool tip when mouse over label

T myLabel.setText( "Text" ) T myLabel.getText() Slide 7

Slide 8

PIC 20A, UCLA, Ivo Dinov

JLabel

JLabel

z Icon

z Alignment

„ Object that implements interface Icon

„ By default, text appears to right of image „ JLabel methods setHorizontalTextPosition and setVerticalTextPosition YSpecify where text appears in label YUse integer constants defined in interface SwingConstants (javax.swing)

„ One class is ImageIcon (.gif and .jpeg images) 24

Icon bug = new ImageIcon( "bug1.gif" );

YAssumed same directory as program (more Chapter 16)

„ Display an icon with setIcon method (of class JLabel) 33

PIC 20A, UCLA, Ivo Dinov

label3.setIcon( bug );

V SwingConstants.LEFT, RIGHT, BOTTOM, CENTER

z Another JLabel constructor T JLabel( "Text", ImageIcon, Text_Alignment_CONSTANT)

YmyLabel.setIcon( myIcon ); YmyLabel.getIcon //returns current Icon

Slide 9

Slide 10

PIC 20A, UCLA, Ivo Dinov

1 // Fig. 12.4: LabelTest.java 2 // Demonstrating the JLabel class. 3 import javax.swing.*; 4 import java.awt.*; 5 import java.awt.event.*; 6 7 public class LabelTest extends JFrame { 8 private JLabel label1, label2, label3; 9 10 public LabelTest() 11 { 12 super( "Testing JLabel" ); 13 Create a Container object, to which we attach 14 Container c = getContentPane(); JLabel objects (subclass of JComponent). 15 c.setLayout( new FlowLayout() ); 16 Initialize text in JLabel constructor. 17 // JLabel constructor with a string argument 18 label1 = new JLabel( "Label with text" ); 19 label1.setToolTipText( "This is label1" ); Set the tool tip text, and attach 20 c.add( label1 ); component to Container c. 21 Create a new ImageIcon (assumed to be 22 // JLabel constructor with string, Icon and in same directory as program). More 23 // alignment arguments Chapter 16. 24 Icon bug = new ImageIcon( "bug1.gif" ); 25 label2 = new JLabel( "Label with text and icon", 26 bug, SwingConstants.LEFT ); 27 label2.setToolTipText( "This is label2" ); 28 c.add( label2 ); Set ImageIcon and alignment 29 of text in JLabel constructor. 30 // JLabel constructor no arguments Slide 11 PIC 20A, UCLA, Ivo Dinov

z1. import

z1.1 Class Labeltest (extends JFrame) z1.2 Declarations

z1.3 getContentPane z2. Initialize JLabels

z2.1 setToolTipText

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 }

PIC 20A, UCLA, Ivo Dinov

label3 = new JLabel(); label3.setText( "Label with icon and text at bottom" ); label3.setIcon( bug ); Use a no-argument constructor. label3.setHorizontalTextPosition( text, icon, and alignment using SwingConstants.CENTER ); methods. label3.setVerticalTextPosition( SwingConstants.BOTTOM ); label3.setToolTipText( "This is label3" ); c.add( label3 );

Set

setSize( 275, 170 ); show(); } public static void main( String args[] ) { LabelTest app = new LabelTest(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); }

PIC 20A, UCLA, Ivo Dinov

z2.2 setHorizontalText Position z2.3 setVerticalText Position z2.3 setToolTipText z3. main 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

Slide 13

PIC 20A, UCLA, Ivo Dinov

Slide 14

Event Handling Model

PIC 20A, UCLA, Ivo Dinov

JTextField and JPasswordField z JTextFields and JPasswordFields

z Delegation event model T Use of event listeners in event handling T Processing of event delegated to particular object

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 Enter pressed in a JTextField T Method actionPerformed called for registered listener T Details in following sections Slide 15

T Single line areas in which text can be entered or displayed T JPasswordFields show inputted text as an asterisk *

T ActionEvent occurs T Currently active field "has the focus"

Slide 16

PIC 20A, UCLA, Ivo Dinov

JTextField and JPasswordField z Methods

PIC 20A, UCLA, Ivo Dinov

JTextField and JPasswordField z Class ActionEvent

T Constructors

T Method getActionCommand

‰JTextField( 10 ) V Textfield with 10 columns of text V Takes average character width, multiplies by 10

‰JTextField( "Hi" )

V Sets text, width determined automatically

‰JTextField( "Hi", 20 )

‰getSource returns Component reference

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 ‰Use getSource to determine which component had event

T getPassword ‰Class JPasswordField ‰Returns password as an array of type char Slide 17

‰Returns text in JTextField that generated event

T Method getSource

PIC 20A, UCLA, Ivo Dinov

‰Display a dialog box when Enter pressed

Slide 18

PIC 20A, UCLA, Ivo Dinov

3

1 // Fig. 12.7: TextFieldTest.java 2 // Demonstrating the JTextField class. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class TextFieldTest extends JFrame { 8 private JTextField text1, text2, text3; 9 private JPasswordField password; 10 11 public TextFieldTest() 12 { 13 super( "Testing JTextField and JPasswordField" ); 14 15 Container c = getContentPane(); 16 c.setLayout( new FlowLayout() ); Create new JTextField 17 objects using the various 18 // construct textfield with default sizing constructors. 19 text1 = new JTextField( 10 ); 20 c.add( text1 ); 21 22 // construct textfield with default text This text field cannot be modified (has 23 text2 = new JTextField( "Enter text here" ); a gray background). It can still 24 c.add( text2 ); 25 generate events. 26 // construct textfield with default text and 27 // 20 visible elements and no event handler 28 text3 = new JTextField( "Uneditable text field", 20 ); 29 text3.setEditable( false ); 30 c.add( text3 ); Slide 19 PIC 20A, UCLA, Ivo Dinov

z1. import z1.1 Declarations z1.2 Constructor z1.3 GUI components z2. Initialize text fields z2.1 setEditable

61

31 32 // construct textfield with default text 33 password = new JPasswordField( "Hidden text" ); 34 c.add( password ); 35 JPasswordField initialized with 36 TextFieldHandler handler = new TextFieldHandler(); text, which appears as asterisks. 37 text1.addActionListener( handler ); 38 text2.addActionListener( handler ); 39 text3.addActionListener( handler ); 40 password.addActionListener( handler ); 41 Register event handlers. Good 42 setSize( 325, 100 ); practice to use an inner class as an 43 show(); event handler. 44 } 45 46 public static void main( String args[] ) 47 { 48 TextFieldTest app = new TextFieldTest(); 49 50 app.addWindowListener( 51 new WindowAdapter() { 52 public void windowClosing( WindowEvent e ) 53 { 54 System.exit( 0 ); 55 } 56 } 57 ); 58 } 59 60 // inner class for event handling Slide 20 PIC 20A, UCLA, Ivo Dinov

z2.2 JPasswordField z2.3 Event handler z3. main

zProgram Output

private class TextFieldHandler implements ActionListener {

62

public void actionPerformed( ActionEvent e )

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

70

else if ( e.getSource() == text3 )

71

s = "text3: " + e.getActionCommand();

72

Use getActionCommand to get the text in the text field that had the event.

else if ( e.getSource() == password ) {

73

JPasswordField pwd =

74

(JPasswordField) e.getSource();

75

s = "password: " +

returns a Component reference, which is cast to a JPasswordField.

e.getSource() new String( pwd.getPassword() );

76 77

}

78 79

JOptionPane.showMessageDialog( null, s );

80

}

81

}

82 }

z4. Inner class TextFieldHandler (event handler) z4.1 getSource z4.2 getActionCommand z4.3 Downcast reference

PIC 20A, UCLA, Ivo Dinov

Slide 21

PIC 20A, UCLA, Ivo Dinov

Slide 22

JButton

How Event Handling Works z Button

z Registering event listeners „ All JComponents contain an object of class EventListenerList called listenerList „ When text1.addActionListener( handler ) executes YNew entry placed into listenerList

T Component user clicks to trigger an action T Several types of buttons Y Command buttons, toggle buttons, check boxes, radio buttons

z Command button T Generates ActionEvent when clicked T Created with class JButton Y Inherits from class AbstractButton

z Handling events

Y Defines many features of Swing buttons

„ When event occurs, has an event ID YComponent uses this to decide which method to call YIf ActionEvent, then actionPerformed called (in all registered ActionListeners)

Slide 23

PIC 20A, UCLA, Ivo Dinov

z JButton T Text on face called button label T Each button should have a different label T Can display Icons Slide 24

PIC 20A, UCLA, Ivo Dinov

4

JButton z Methods of class JButton „ Constructors JButton myButton = new JButton( "Label" ); JButton myButton = new JButton( "Label", myIcon );

T setRolloverIcon( myIcon ) YSets image to display when mouse over button

z Class ActionEvent „ getActionCommand YReturns label of button that generated event

Slide 25

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 }

PIC 20A, UCLA, Ivo Dinov

z1. import z1.1 Declarations z2. Initialize buttons and Icons z2.1 setRolloverIcon z2.2 Register event handler

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

the

plainButton.addActionListener( handler );

zProgram Output

z3. main

setSize( 275, 100 ); show(); } public static void main( String args[] ) { ButtonTest app = new ButtonTest();

z4. Inner class event handler

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

getActionCommand returns label of button that generated event.

}

// inner class for button event handling private class ButtonHandler implements ActionListener { public void actionPerformed( ActionEvent e ) { JOptionPane.showMessageDialog( null, "You pressed: " + e.getActionCommand() ); } }

PIC 20A, UCLA, Ivo Dinov

Slide 27

PIC 20A, UCLA, Ivo Dinov

JCheckBox and JRadioButton z State buttons

Slide 28

JCheckBox and JRadioButton z When JCheckBox changes

„ JToggleButton YSubclasses JCheckBox, JRadioButton

„ ItemEvent generated YHandled by an ItemListener, which must define itemStateChanged

„ Have on/off (true/false) values

„ Register handlers with with addItemListener

z Class JCheckBox

51 55

„ Text appears to right of checkbox „ Constructor

56

JCheckBox myBox = new JCheckBox( "Title" );

private class CheckBoxHandler implements ItemListener { public void itemStateChanged( ItemEvent e ) {

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

JCheckBox and JRadioButton

z1. import

z JTextField „ Method setText( fontObject ) Ynew Font( name, style_CONSTANT, size ) Ystyle_CONSTANT - FONT.PLAIN, BOLD, ITALIC V Can add to get combinations

z Example „ Use JCheckBoxes to change the font of a JTextField

Slide 31

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

1 // CheckBoxTest.java 2 // Creating Checkbox buttons. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class CheckBoxTest extends JFrame { 8 private JTextField t; 9 private JCheckBox bold, italic; 10 11 public CheckBoxTest() 12 { 13 super( "JCheckBox Test" ); 14 15 Container c = getContentPane(); 16 c.setLayout(new FlowLayout()); 17 18 t = new JTextField( "Watch the font style change", 20 ); 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 32 PIC 20A, UCLA, Ivo Dinov

PIC 20A, UCLA, Ivo Dinov

z1.1 Declarations z1.2 Initialize JCheckBoxes z1.3 Register event handler

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

z2. main z3. Inner class (event handler) z3.1 getStateChange

setSize( 275, 100 ); show(); } public static void main( String { new CheckBoxTest(); }

Because CheckBoxHandler implements ItemListener, it must define method args[] ) itemStateChanged

62 63 64 65 66 67 68 69 70 71 72 73 74 }

if ( e.getSource() == italic ) if ( e.getStateChange() == ItemEvent.SELECTED ) valItalic = Font.ITALIC; else valItalic = Font.PLAIN;

zProgram Output

t.setFont( new Font( "TimesRoman", valBold + valItalic, 14 ) ); t.repaint();

Use setFont to update the JTextField.

} }

private class CheckBoxHandler implements ItemListener { getStateChange returns private int valBold = Font.PLAIN; ItemEvent.SELECTED or private int valItalic = Font.PLAIN;

ItemEvent.DESELECTED

public void itemStateChanged( ItemEvent e ) { if ( e.getSource() == bold ) if ( e.getStateChange() == ItemEvent.SELECTED ) valBold = Font.BOLD; else valBold = Font.PLAIN;

PIC 20A, UCLA, Ivo Dinov

Slide 33

PIC 20A, UCLA, Ivo Dinov

JCheckBox and JRadioButton

Slide 34

JCheckBox and JRadioButton z Class JRadioButton

z Radio buttons T Have two states: selected and deselected T Normally appear as a group YOnly one radio button in the group can be selected at time YSelecting one button forces the other buttons off

T Mutually exclusive options T ButtonGroup - maintains logical relationship between radio buttons

z Class JRadioButton

T Generates ItemEvents (like JCheckBox)

z Class ButtonGroup T ButtonGroup myGroup = new ButtonGroup(); T Binds radio buttons into logical relationship T Method add YAssociate a radio button with a group 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 2 // Creating radio buttons using ButtonGroup and JRadioButton. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class RadioButtonTest extends JFrame { 8 private JTextField t; 9 private Font plainFont, boldFont, 10 italicFont, boldItalicFont; 11 private JRadioButton plain, bold, italic, boldItalic; 12 private ButtonGroup radioGroup; 13 14 public RadioButtonTest() 15 { 16 super( "RadioButton Test" ); 17 18 Container c = getContentPane(); 19 c.setLayout( new FlowLayout() ); Initialize radio buttons. 20 21 t = new JTextField( "Watch the font styleone change", 25 selected. ); is initially 22 c.add( t ); 23 24 // Create radio buttons 25 plain = new JRadioButton( "Plain", true ); 26 c.add( plain ); 27 bold = new JRadioButton( "Bold", false); 28 c.add( bold ); 29 italic = new JRadioButton( "Italic", false ); 30 c.add( italic ); Slide 37 PIC 20A, UCLA, Ivo Dinov

z1. import z1.1 Declarations z1.2 Initialization

Only

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 } 69 } 70 ); 71 } 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 } Slide 39 PIC 20A, UCLA, Ivo Dinov

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

boldItalic = new JRadioButton( "Bold/Italic", false ); c.add( boldItalic ); // register events RadioButtonHandler handler = new RadioButtonHandler(); plain.addItemListener( handler ); Create a ButtonGroup. Only bold.addItemListener( handler ); one radio button in the group may italic.addItemListener( handler ); be selected at a time. boldItalic.addItemListener( handler ); // create logical relationship between JRadioButtons radioGroup = new ButtonGroup(); Method add adds radio radioGroup.add( plain ); buttons to the ButtonGroup radioGroup.add( bold ); radioGroup.add( italic ); radioGroup.add( boldItalic ); plainFont = new Font( "TimesRoman", Font.PLAIN, 14 ); boldFont = new Font( "TimesRoman", Font.BOLD, 14 ); italicFont = new Font( "TimesRoman", Font.ITALIC, 14 ); boldItalicFont = new Font( "TimesRoman", Font.BOLD + Font.ITALIC, 14 ); t.setFont( plainFont );

z2. Register event handler z2.1 ButtonGroup

setSize( 300, 100 ); show();

z2.2 add

}

Slide 38

PIC 20A, UCLA, Ivo Dinov

z3. main

z4. Inner class (event handler)

Program Output

Slide 40

PIC 20A, UCLA, Ivo Dinov

JComboBox

JComboBox

z JComboBox methods

z Combo box (drop down list)

„ getSelectedIndex

„ List of items, user makes a selection „ Class JComboBox

YReturns the index of the currently selected item YmyComboBox.getSelectedIndex()

YGenerate ItemEvents

„ setMaximumRowCount( n )

z JComboBox „ Constructor JComboBox ( arrayOfNames )

„ Numeric index keeps track of elements YFirst element added at index 0 YFirst item added is appears as currently selected item when combo box appears

Slide 41

PIC 20A, UCLA, Ivo Dinov

YSet max number of elements to display when user clicks combo box YScrollbar automatically provided YsetMaximumRowCount( 3 )

z Example „ Use JComboBox to set the Icon for a JLabel Slide 42

PIC 20A, UCLA, Ivo Dinov

7

1 // Fig. 29.13: ComboBoxTest.java 2 // Using a JComboBox to select an image to display. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class ComboBoxTest extends JFrame { 8 private JComboBox images; 9 private JLabel label; 10 private String names[] = 11 { "bug1.gif", "bug2.gif", 12 "travelbug.gif", "buganim.gif" }; 13 private Icon icons[] = 14 { new ImageIcon( names[ 0 ] ), 15 new ImageIcon( names[ 1 ] ), 16 new ImageIcon( names[ 2 ] ), 17 new ImageIcon( names[ 3 ] ) }; 18 19 public ComboBoxTest() Initialize JComboBox with 20 { 21 super( "Testing JComboBox" ); an array of Strings. 22 23 Container c = getContentPane(); 24 c.setLayout( new FlowLayout() ); 25 26 images = new JComboBox( names ); Set the number of rows 27 images.setMaximumRowCount( 3 ); displayed at a time. 28 29 images.addItemListener( 30 new ItemListener() { Slide 43 PIC 20A, UCLA, Ivo Dinov

z1. import z1.1 Initialization z1.2 Constructor z2. Initialize JComboBox z2.1 setMaximumRowCount z2.2 Register ItemListener (anonymous inner class)

to be

31 public void itemStateChanged( ItemEvent e ) 32 { 33 label.setIcon( 34 icons[ images.getSelectedIndex() ] ); 35 } 36 } 37 ); 38 Use method getSelectedIndex 39 c.add( images ); to determine which Icon to use. 40 41 label = new JLabel( icons[ 0 ] ); 42 c.add( label ); 43 44 setSize( 350, 100 ); 45 show(); 46 } 47 48 public static void main( String args[] ) 49 { 50 ComboBoxTest app = new ComboBoxTest(); 51 52 app.addWindowListener( 53 new WindowAdapter() { 54 public void windowClosing( WindowEvent e ) 55 { 56 System.exit( 0 ); 57 } 58 } 59 ); 60 } 61 } Slide 44 PIC 20A, UCLA, Ivo Dinov

z2.3 getSelectedIndex z3. main

JList

JList

z JScrollPane object used for scrolling

z List „ Displays series of items, may select one or more „ This section, discuss single-selection lists

40

c.add( new JScrollPane( colorList ) );

„ Takes component to which to add scrolling as argument „ Add JScrollPane object to content pane

z Class JList

z JList methods

„ Constructor JList( arrayOfNames )

„ setSelectionMode( selection_CONSTANT ) „ SINGLE_SELECTION

YTakes array of Objects (Strings) to display in list

„ setVisibleRowCount( n )

YOne item selected at a time

YDisplays n items at a time

„ SINGLE_INTERVAL_SELECTION

YDoes not provide automatic scrolling

YMultiple selection list, allows contiguous items to be selected

„ MULTIPLE_INTERVAL_SELECTION

YMultiple-selection list, any items can be selected Slide 45

1 2 3 4 5 6 7

JList z JList methods

8 9 10 11 12 13 14

„ getSelectedIndex() YReturns index of selected item

z Event handlers „ Implement interface ListSelectionListener (javax.swing.event) „ Define method valueChanged „ Register handler with addListSelectionListener

z Example „ Use a JList to select the background color Slide 47

Slide 46

PIC 20A, UCLA, Ivo Dinov

PIC 20A, UCLA, Ivo Dinov

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

PIC 20A, UCLA, Ivo Dinov

// ListTest.java // Selecting colors from a JList. import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*;

z1. import z1.1 Declarations z1.2 Initialize colorNames and colors public class ListTest extends JFrame { private JList colorList; z1.3 Constructor private Container c;

private String colorNames[] = { "Black", "Blue", "Cyan", "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", "Orange", "Pink", "Red", "White", "Yellow" }; private Color colors[] = { Color.black, Color.blue, Color.cyan, Color.darkGray, Color.gray, Color.green, Color.lightGray, Color.magenta, Color.orange, Color.pink, Color.red, Color.white, Color.yellow }; public ListTest() { super( "List Test" ); c = getContentPane(); c.setLayout( new FlowLayout() );

PIC 20A, UCLA, Ivo Dinov

Slide 48

8

30 // create a list with the items in the colorNames array 31 colorList = new JList( colorNames ); Initialize JList with array of 32 colorList.setVisibleRowCount( 5 ); Strings, and show 5 items at 33 a time. 34 // do not allow multiple selections 35 colorList.setSelectionMode( 36 ListSelectionModel.SINGLE_SELECTION ); Make the JList a single37 selection list. 38 // add a JScrollPane containing the JList 39 // to the content pane 40 c.add( new JScrollPane( colorList ) ); Create a new JScrollPane 41 object, initialize it with a JList, 42 // set up event handler and attach it to the content pane. 43 colorList.addListSelectionListener( 44 new ListSelectionListener() { Change 45 public void valueChanged( ListSelectionEvent e ) the color according to the item 46 { selected (use getSelectedIndex). 47 c.setBackground( 48 colors[ colorList.getSelectedIndex() ] ); 49 } 50 } 51 ); 52 53 setSize( 350, 150 ); 54 show(); 55 } 56 57 public static void main( String args[] ) 58 { 59 ListTest app = new ListTest(); Slide 49 PIC 20A, UCLA, Ivo Dinov

60 61

app.addWindowListener(

62

new WindowAdapter() {

63

public void windowClosing( WindowEvent e )

64

{

65

System.exit( 0 );

66

}

67

}

68

);

69

}

70 }

zProgram Output

z2. Create JList z2.1 setVisibleRowCount z2.2 setSelectionMode z2.3 JScrollPane z3. Event handler z4. main

Slide 50

PIC 20A, UCLA, Ivo Dinov

Multiple-Selection Lists

Multiple-Selection Lists z JList methods

z Multiple selection lists „ SINGLE_INTERVAL_SELECTION

„ setFixedCellHeight( height ) YSpecifies height in pixels of each item in JList

YSelect a contiguous group of items by holding Shift key

„ MULTIPLE_INTERVAL_SELECTION

„ setFixedCellWidth( width )

YSelect any amount of items YHold Ctrl key and click each item to select

YAs above, set width of list

z Example

z JList methods

„ Have two multiple-selection lists „ Copy button copies selected items in first list to other list

„ getSelectedValues() YReturns an array of Objects representing selected items

„ setListData( arrayOfObjects ) YSets items of JList to elements in arrayOfObjects Slide 51

z1. import z1.1 Initialize colorNames 3 import javax.swing.*; z1.2 Initialize JList 4 import java.awt.*; 5 import java.awt.event.*; z1.3 setVisibleRowCount 6 7 public class MultipleSelection extends JFrame z1.4{ setFixedCellHeight 8 private JList colorList, copyList; z1.5 setSelectionMode 9 private JButton copy; 10 private String colorNames[] = z1.6 JScrollPane 11 { "Black", "Blue", "Cyan", "Dark Gray", "Gray", 1

// MultipleSelection.java

2

// Copying items from one List to another.

12

"Green", "Light Gray", "Magenta", "Orange", "Pink",

13

"Red", "White", "Yellow" };

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

public MultipleSelection() { super( "Multiple Selection Lists" ); Container c = getContentPane(); c.setLayout( new FlowLayout() );

Initialize the JList with an array of Strings. Specify the number of items to appear at a time. Set the cell height

colorList = new JList( colorNames ); Specify that list is to be colorList.setVisibleRowCount( 5 ); MULTIPLE_INTERVAL_SELECTION colorList.setFixedCellHeight( 15 ); colorList.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION ); c.add( new JScrollPane( colorList ) );

PIC 20A, UCLA, Ivo Dinov

Slide 53

Slide 52

PIC 20A, UCLA, Ivo Dinov

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

PIC 20A, UCLA, Ivo Dinov

// create copy button copy = new JButton( "Copy >>>" ); copy.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { // place selected values in copyList copyList.setListData( colorList.getSelectedValues() ); } } Use the array returned by ); getSelectedValues c.add( copy );

to set

the items of copyList.

copyList = new JList( ); copyList.setVisibleRowCount( 5 ); copyList.setFixedCellWidth( 100 ); copyList.setFixedCellHeight( 15 ); copyList.setSelectionMode( ListSelectionModel.SINGLE_INTERVAL_SELECTION ); c.add( new JScrollPane( copyList ) ); setSize( 300, 120 ); show(); }

PIC 20A, UCLA, Ivo Dinov

z2. JButton z2.1 Event handler (anonymous inner class) z2.2 setListData z2.2.1 getSelectedValues z2.3 Initialize JList Slide 54

9

55 56 57 58 59 60 61 62 63 64 65 66 67 68 }

public static void main( String args[] ) { MultipleSelection app = new MultipleSelection();

Mouse Event Handling

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

z Mouse events „ Can be trapped for any GUI component derived from java.awt.Component „ Mouse event handling methods

}

‰Take a MouseEvent object V Contains info about event, including x and y coordinates V Methods getX and getY

z3. main

„ Interfaces MouseListener and MouseMotionListener

zProgram Output

‰addMouseListener ‰addMouseMotionListener ‰Must define all methods Slide 55

PIC 20A, UCLA, Ivo Dinov

Slide 56

Mouse Event Handling

PIC 20A, UCLA, Ivo Dinov

Mouse Event Handling

z Interface MouseListener

z Interface MouseMotionListener T public void mouseDragged( MouseEvent e )

T public void mousePressed( MouseEvent e )

‰Mouse pressed and moved

‰Mouse pressed on a component

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

‰Mouse released

getContentPane().add( statusBar, BorderLayout.SOUTH );

T Adds component statusBar to the bottom portion of the content pane

T public void mouseEntered( MouseEvent e ) ‰Mouse enters bounds of component

T public void mouseExited( MouseEvent e ) ‰Mouse leaves bounds of component

Slide 57

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

30

// MouseTracker.java // Demonstrating mouse events. import java.awt.*; import java.awt.event.*; import javax.swing.*;

Class implements interfaces MouseListener and MouseMotionListener to listen for mouse events. There are seven methods to define.

at the bottom of the content pane. More later.

public MouseTracker() { super( "Demonstrating Mouse Events" );

}

Application is its own event handler

z1. import z1. Class MouseTracker (implements MouseListener, MouseMotion Listener)

// MouseListener event handlers public void mouseClicked( MouseEvent e ) {

z1.2 Register event handlers (this) z2. Define event handler methods

PIC 20A, UCLA, Ivo Dinov

Slide 59

", " + e.getY() + "]" ); }

37 38 39 40 41 42

getX and getY return the coordinates of where the mouse event occurred.

public void mousePressed( MouseEvent e ) { statusBar.setText( "Pressed at [" + e.getX() + ", " + e.getY() + "]" ); } public void mouseReleased( MouseEvent e ) { statusBar.setText( "Released at [" + e.getX() +

43

statusBar = new JLabel(); getContentPane().add( statusBar, BorderLayout.SOUTH ); // application listens to its own mouse events addMouseListener( this ); addMouseMotionListener( this );

32 33 34 35 36

PIC 20A, UCLA, Ivo Dinov

statusBar.setText( "Clicked at [" + e.getX() +

31

public class MouseTracker extends JFrame implements MouseListener, MouseMotionListener { private JLabel statusBar; Puts the JLabel component

setSize( 275, 100 ); show();

Slide 58

PIC 20A, UCLA, Ivo Dinov

", " + e.getY() + "]" );

44 45 46 47 48 49 50 51 52 53

}

54 55 56 57 58 59

}

public void mouseEntered( MouseEvent e ) { statusBar.setText( "Mouse in window" ); }

z2.1 getX and getY

public void mouseExited( MouseEvent e ) { statusBar.setText( "Mouse outside window" );

// MouseMotionListener event handlers public void mouseDragged( MouseEvent e ) { statusBar.setText( "Dragged at [" + e.getX() +

60

", " + e.getY() + "]" ); PIC 20A, UCLA, Ivo Dinov

Slide 60

10

61 62 63 64 65

} public void mouseMoved( MouseEvent e ) { statusBar.setText( "Moved at [" + e.getX() +

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 }

z3. main

", " + e.getY() + "]" ); } public static void main( String args[] ) { MouseTracker app = new MouseTracker(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) {

zProgram Output

System.exit( 0 ); } } ); }

Slide 61

PIC 20A, UCLA, Ivo Dinov

Slide 62

PIC 20A, UCLA, Ivo Dinov

Adapter Classes z Time consuming to define all interface methods T MouseListener and MouseMotionListener have seven methods YWhat if we only want to use one? YRequired to define all methods in interface

z Adapter class T Implements an interface YDefault implementation (empty body) for all methods

Adapter Classes z Adapter classes ComponentAdapter ContainerAdapter FocusAdapter KeyAdapter MouseAdapter MouseMotionAdapter WindowAdapter

ComponentListener ContainerListener FocusListener KeyListener MouseListener MouseMotionListener 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

Slide 64

PIC 20A, UCLA, Ivo Dinov

Adapter Classes 18 19

addMouseMotionListener( new MouseMotionAdapter() {

PIC 20A, UCLA, Ivo Dinov

Adapter Classes 40

Painter app = new Painter();

42

app.addWindowListener(

20

public void mouseDragged( MouseEvent e )

43

21

{

44

public void windowClosing( WindowEvent e )

45

{

T Anonymous inner class

new WindowAdapter() {

46

YExtends MouseMotionAdapter (which implements MouseMotionListener) YInner class gets default (empty body) implementation of mouseMoved and mouseDragged YOverride methods want to use

System.exit( 0 );

47

}

48 49

} );

T Used in applications extending JFrame T Interface WindowListener specifies seven methods Y WindowAdapter define these for us

T Only override the method we want Y windowClosing Y Enables use of close button Slide 65

PIC 20A, UCLA, Ivo Dinov

Slide 66

PIC 20A, UCLA, Ivo Dinov

11

Adapter Classes z Example program T Simple paint program T Draw oval whenever user drags mouse T Only want to define method mouseDragged YUse MouseMotionAdapter

Slide 67

PIC 20A, UCLA, Ivo Dinov

1 // Painter.java 2 // Using class MouseMotionAdapter. 3 import javax.swing.*; 4 import java.awt.event.*; 5 import java.awt.*; 6 7 public class Painter extends JFrame { 8 private int xValue = -10, yValue = -10; 9 10 public Painter() 11 { 12 super( "A simple paint program" ); 13 Use adapter class so we do not have to define all the 14 getContentPane().add( methods of interface MouseMotionListner. 15 new Label( "Drag the mouse to draw" ), 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 68 PIC 20A, UCLA, Ivo Dinov

z1. import

z1.1 addMouseMotion Listener 1.2. MouseMotionAdapter

32 33

public void paint( Graphics g )

34

{

35

Adapter Classes

Draw an oval based at location xValue, yValue.

g.fillOval( xValue, yValue, 4, 4 );

36

}

z Class MouseEvent

37 38

public static void main( String args[] )

39

{

40

T Inherits from InputEvent

Painter app = new Painter();

T Can distinguish between buttons on multi-button mouse

41 42

app.addWindowListener(

43

YCombination of a mouse click and a keystroke

new WindowAdapter() {

44

public void windowClosing( WindowEvent e )

45

{

46

T Java assumes every mouse has a left mouse button YAlt + click = center mouse button YMeta + click = right mouse button

System.exit( 0 );

47

}

48

}

49

);

50

}

51 }

z2. paint

T Method getClickCount

z3. main

T Methods isAltDown and isMetaDown

YReturns number of mouse clicks (separate for each button) YReturns true if Alt or Meta key down when mouse clicked

z3.1 addWindowListener z3.2 WindowAdapter Slide 69

PIC 20A, UCLA, Ivo Dinov

Slide 70

Adapter Classes z Class JFrame T Method setTitle( "String" ) YSets title bar of window

1 2

// MouseDetails.java // Demonstrating mouse clicks and

3 4 5 6 7 8 9

// distinguishing between mouse buttons. import javax.swing.*; import java.awt.*; import java.awt.event.*;

z1. import

public class MouseDetails extends JFrame { private String s = "";

z1.1 Constructor

10 11 12 13 14 15 16

PIC 20A Spring 2002 – Home Page Prof. I.D. Dinov

17 18 19 20 21 22 23 24 25 26 27

Slide 71

PIC 20A, UCLA, Ivo Dinov

PIC 20A, UCLA, Ivo Dinov

private int xPos, yPos; public MouseDetails() { super( "Mouse clicks and buttons" );

z1.2 Register event handler z2. paint

addMouseListener( new MouseClickHandler() ); setSize( 350, 150 ); show(); } public void paint( Graphics g ) { g.drawString( "Clicked @ [" + xPos + ", " + yPos + "]", xPos, yPos ); }

PIC 20A, UCLA, Ivo Dinov

Slide 72

12

28 public static void main( String args[] ) 29 { 30 MouseDetails app = new MouseDetails(); 31 32 app.addWindowListener( 33 new WindowAdapter() { 34 public void windowClosing( WindowEvent e ) 35 { 36 System.exit( 0 ); Use a named inner class as the event handler. Can still 37 } inherit from MouseAdapter (extends MouseAdapter). 38 } 39 ); 40 } 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 52 if ( e.isMetaDown() ) // Right mouse button 53 s += " with right mouse button"; 54 else if ( e.isAltDown() ) // Middle mouse button 55 s += " with center mouse button"; 56 else // Left mouse button 57 s += " with left mouse button"; 58 Slide 73 PIC 20A, UCLA, Ivo Dinov

59 60 61 62 63 }

setTitle( s );

// set the title bar of the window

repaint(); }

Set the title bar.

}

z4.4 setTitle zProgram Output

z3. main z4. Inner class (event handler) z4.1 getClickCount z4.2 isMetaDown z4.3 isAltDown

Keyboard Event Handling

Keyboard Event Handling

z Interface KeyListener

z KeyEvent methods „ getKeyCode

„ Handles key events (keys pressed on keyboard) „ Must define methods

‰Every key represented with a virtual key code (constant) ‰Complete list in on-line documentation (java.awt.event)

‰keyPressed - called when any key pressed ‰keyTyped - called when non-action key pressed

„ getKeyText

V Action keys: arrow keys, home, end, page up, page down, function keys, num lock, print screen, scroll lock, caps lock, pause

‰Takes key code constant, returns name of key

„ getKeyChar

‰keyReleased - called for any key after it is released ‰Each get a KeyEvent as an argument

‰Gets Unicode character of key pressed

„ isActionKey

V Subclass of InputEvent

Slide 75

‰Returns true if key that generated event is an action key

Slide 76

PIC 20A, UCLA, Ivo Dinov

Keyboard Event Handling z KeyEvent methods „ getModifiers (from class InputEvent) ‰Returns which modifiers were pressed

„ getKeyModifierText ( e.getModifiers ) ‰Returns string containing names of modifier keys

z Upcoming example „ Create a JTextArea „ Modify text depending on what keys are pressed

Slide 77

Slide 74

PIC 20A, UCLA, Ivo Dinov

PIC 20A, UCLA, Ivo Dinov

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

PIC 20A, UCLA, Ivo Dinov

// KeyDemo.java // Demonstrating keystroke events. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class KeyDemo extends JFrame implements KeyListener { private String line1 = "", line2 = ""; private String line3 = ""; Class implements interface private JTextArea textArea;

KeyListener, so it must define the three required methods.

public KeyDemo() { super( "Demonstrating Keystroke Events" ); textArea = new JTextArea( 10, 15 ); textArea.setText( "Press any key on the keyboard..." ); textArea.setEnabled( false ); // allow frame to process Key events addKeyListener( this );

Register the event handler.

getContentPane().add( textArea ); setSize( 350, 100 ); show(); }

PIC 20A, UCLA, Ivo Dinov

z1. import z1.1 Class KeyDemo (implements KeyListener) z1.2 addKeyListener Slide 78

13

29 public void keyPressed( KeyEvent e ) 30 { 31 line1 = "Key pressed: " + 32 e.getKeyText( e.getKeyCode() ); 33 setLines2and3( e ); 34 } getKeyCode returns the virtual key code. 35 getKeyText converts the key code to a 36 public void keyReleased( KeyEvent e ) String containing the name. 37 { 38 line1 = "Key released: " + 39 e.getKeyText( e.getKeyCode() ); 40 setLines2and3( e ); 41 } 42 43 public void keyTyped( KeyEvent e ) 44 { 45 line1 = "Key typed: " + e.getKeyChar(); 46 setLines2and3( e ); 47 } 48 Test if the key is 49 private void setLines2and3( KeyEvent e ) an action key 50 { 51 line2 = "This key is " + 52 ( e.isActionKey() ? "" : "not " ) + 53 "an action key"; getModifiers returns the 54 modifier keys, and 55 String temp = getKeyModifersText 56 e.getKeyModifiersText( e.getModifiers() ); turns them into a String. 57 58 line3 = "Modifier keys pressed: " + 59 ( temp.equals( "" ) ? "none" : temp ); 60 Slide 79 PIC 20A, UCLA, Ivo Dinov

z2. Event handling methods z2.1 getKeyText z2.2 getKeyCode z2.3 isActionKey z2.4 Determine modifier keys

61

textArea.setText(

62 63

z3. main

line1 + "\n" + line2 + "\n" + line3 + "\n" ); }

64 65

public static void main( String args[] )

66

{

67

KeyDemo app = new KeyDemo();

68 69

app.addWindowListener(

70

new WindowAdapter() {

71

public void windowClosing( WindowEvent e )

72

{

73

System.exit( 0 );

74

}

75

}

76 77

); }

78 }

Slide 80

PIC 20A, UCLA, Ivo Dinov

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

Slide 81

PIC 20A, UCLA, Ivo Dinov

Slide 82

FlowLayout z Most basic layout manager „ Components placed left to right in order added „ When edge of container reached, continues on next line „ Components can be left-aligned, centered (default), or right-aligned

z FlowLayout methods „ setAlignment( position_CONSTANT ) ‰FlowLayout.LEFT, FlowLayout.CENTER, FlowLayout.RIGHT

„ layoutContainer( container ) ‰Update Container specified with layout V I.e., content pane Slide 83

PIC 20A, UCLA, Ivo Dinov

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

// FlowLayoutDemo.java // Demonstrating FlowLayout alignments. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class FlowLayoutDemo extends JFrame { private JButton left, center, right; private Container c; private FlowLayout layout; public FlowLayoutDemo() { super( "FlowLayout Demo" ); layout = new FlowLayout(); c = getContentPane(); c.setLayout( layout );

PIC 20A, UCLA, Ivo Dinov

z1. import z1.1 Declarations z1.2 Initialize FlowLayout z1.3 Create button z1.4 Event handler z1.4.1 setAlignment z1.4.2 layoutContainer

setAlignment changes the alignment of the layout. Use method layoutContainer to update changes

left = new JButton( "Left" ); left.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { layout.setAlignment( FlowLayout.LEFT );

27 28 // re-align attached components 29 layout.layoutContainer( c ); 30 } Slide 84 PIC 20A, UCLA, Ivo Dinov

14

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

} ); c.add( left ); center = new JButton( "Center" ); center.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e ) { layout.setAlignment( FlowLayout.CENTER ); // re-align attached components layout.layoutContainer( c ); } } ); c.add( center );

z1.5 add JButton z2. JButton z2.1 Event handler z3. JButton

right = new JButton( "Right" ); right.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e )

z3.1 Event handler

61 62 63 64 65 66 67 68 69

c.add( right ); setSize( 300, 75 ); show(); }

z4. main

public static void main( String args[] ) { FlowLayoutDemo app = new FlowLayoutDemo();

70 71 72 73

app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e )

74 75 76 77 78 79 80 }

zProgram Output

{ System.exit( 0 ); } } ); }

{ layout.setAlignment( FlowLayout.RIGHT );

55 56 // re-align attached components 57 layout.layoutContainer( c ); 58 } 59 } 60 ); Slide 85 PIC 20A, UCLA, Ivo Dinov

Slide 86

PIC 20A, UCLA, Ivo Dinov

BorderLayout

BorderLayout z Methods

z BorderLayout

„ Constructor: BorderLayout( hGap, vGap );

„ Default manager for content pane „ Arrange components into 5 regions

YhGap - horizontal gap space between regions YvGap - vertical gap space between regions YDefault is 0 for both

YNorth, south, east, west, center

„ Up to 5 components can be added directly

„ Adding components

YOne for each region

YmyContainer.add( component, position ) Ycomponent - component to add Yposition - BorderLayout.NORTH

„ Components placed in YNorth/South - Region is as tall as component YEast/West - Region is as wide as component YCenter - Region expands to take all remaining space

Slide 87

Slide 88

PIC 20A, UCLA, Ivo Dinov

BorderLayout z Methods „ setVisible( boolean ) ( in class JButton) YIf false, hides component

„ layoutContainer( container ) - updates container, as before

Slide 89

V SOUTH, EAST, WEST, CENTER similar

PIC 20A, UCLA, Ivo Dinov

1 2 3 4 5 6 7 8

PIC 20A, UCLA, Ivo Dinov

// BorderLayoutDemo.java // Demonstrating BorderLayout. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class BorderLayoutDemo extends JFrame implements ActionListener {

9 10 11

private JButton b[]; private String names[] = { "Hide North", "Hide South", "Hide East",

12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

"Hide West", "Hide Center" }; private BorderLayout layout; public BorderLayoutDemo() { super( "BorderLayout Demo" );

Set horizontal and vertical spacing in constructor.

layout = new BorderLayout( 5, 5 ); Container c = getContentPane(); c.setLayout( layout ); // instantiate button objects b = new JButton[ names.length ]; for ( int i = 0; i < names.length; i++ ) {

28 b[ i ] = new JButton( names[ i ] ); 29 b[ i ].addActionListener( this ); 30 } Slide PIC 20A, UCLA, Ivo Dinov

z1. import z1.1 Declarations z1.2 Initialize layout z1.3 Create JButtons z1.4 Register event handler

90

15

31 32 33

61

public void windowClosing( WindowEvent e )

// order not important c.add( b[ 0 ], BorderLayout.NORTH );

// North position

62

{

34

c.add( b[ 1 ], BorderLayout.SOUTH );

// South position

63

35

c.add( b[ 2 ], BorderLayout.EAST );

// East position

64

36

c.add( b[ 3 ], BorderLayout.WEST );

// West position

65

37

c.add( b[ 4 ], BorderLayout.CENTER ); // Center position

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

System.exit( 0 ); }

);

67 setSize( 300, 200 ); show();

zProgram Output

}

66 }

68 }

} public void actionPerformed( ActionEvent e ) { for ( int i = 0; i < b.length; i++ ) if ( e.getSource() == b[ i ] ) b[ i ].setVisible( false ); else b[ i ].setVisible( true ); // re-layout the content pane layout.layoutContainer( getContentPane() ); }

Hide the button that generated the event.

Recalculates layout of content pane.

z2. add (specify position) z3. actionPerformed z3.1 setVisible z3.2 layoutContainer z4. main

public static void main( String args[] ) { BorderLayoutDemo app = new BorderLayoutDemo();

58 59 app.addWindowListener( 60 new WindowAdapter() { PIC 20A, UCLA, Ivo Dinov

Slide 91

PIC 20A, UCLA, Ivo Dinov

zProgram Output

Slide 92

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 Slide 93

PIC 20A, UCLA, Ivo Dinov

Slide 94

1 2 3 4 5 6 7 8

GridLayout z Updating containers „ Container method validate YRe-layouts a container for which the layout has changed

„ Example: Container c = getContentPane; c.setLayout( myLayout ); if ( x = 3 ){ c.setLayout( myLayout2 ); c.validate(); } YChanges layout and updates c if condition met

9 10 11

PIC 20A, UCLA, Ivo Dinov

// GridLayoutDemo.java // Demonstrating GridLayout. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GridLayoutDemo extends JFrame implements ActionListener { private JButton b[]; private String names[] = { "one", "two", "three", "four", "five", "six" };

12 private boolean toggle = true; 13 private Container c; 14 private GridLayout grid1, grid2; 15 Create two GridLayouts, 16 public GridLayoutDemo() a 2 by 3 and a 3 by 2 (rows, 17 { columns). 18 super( "GridLayout Demo" ); 19 20 grid1 = new GridLayout( 2, 3, 5, 5 ); 21 grid2 = new GridLayout( 3, 2 ); 22 23 c = getContentPane(); 24 c.setLayout( grid1 ); 25 26 // create and add buttons 27 b = new JButton[ names.length ]; 28 29 for (int i = 0; i < names.length; i++ ) { 30 b[ i ] = new JButton( names[ i ] ); 31 b[ i ].addActionListener( this ); Slide 96 PIC 20A, UCLA, Ivo Dinov

z1. import

z1.1 Declarations z1.2 Initialize layout z1.3 Register event handler

Slide 95

PIC 20A, UCLA, Ivo Dinov

16

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

c.add( b[ i ] ); } setSize( 300, 150 ); show();

Add buttons to layout. Added from left to right in order.

zProgram Output

} public void actionPerformed( ActionEvent e ) { if ( toggle ) Toggle layouts and c.setLayout( grid2 ); update content pane else with validate. c.setLayout( grid1 ); toggle = !toggle; c.validate(); }

z1.4 add z2. actionPerformed

public static void main( String args[] ) { GridLayoutDemo app = new GridLayoutDemo();

z3. main

app.addWindowListener( new WindowAdapter() { 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

Panels

Slide 98

Panels

z Complex GUIs „ Each component needs to be placed in an exact location „ Can use multiple panels

z Usage „ Create panels, and set the layout for each „ Add components to the panels as needed „ Add the panels to the content pane (default BorderLayout)

YEach panel's components arranged in a specific layout

z Panels „ 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

Slide 100

PIC 20A, UCLA, Ivo Dinov

1 // PanelDemo.java 2 // Using a JPanel to help lay out components. 3 import java.awt.*; 4 import java.awt.event.*; 5 import javax.swing.*; 6 7 public class PanelDemo extends JFrame { 8 private JPanel buttonPanel; 9 private JButton buttons[]; 10 11 public PanelDemo() 12 { 13 super( "Panel Demo" ); 14 15 Container c = getContentPane(); Create a new panel. 16 buttonPanel = new JPanel(); 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 ] ); Add components to panel. 25 } 26 27 c.add( buttonPanel, BorderLayout.SOUTH ); 28 Add panel to the content pane 29 setSize( 425, 150 ); (BorderLayout.SOUTH). 30 show(); 31 } Slide 101 PIC 20A, UCLA, Ivo Dinov

z1. import z1.1 Declarations z1.2 Initialize buttonPanel z1.3 GridLayout z1.4 ButtonPanel.add z1.5 c.add

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 }

PIC 20A, UCLA, Ivo Dinov

public static void main( String args[] ) { PanelDemo app = new PanelDemo(); app.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } );

z2. main zProgram Output

}

JPanel sized to its components. Grows as needed.

PIC 20A, UCLA, Ivo Dinov

Slide 102

17