Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 13 - Graphical User Interface Components: Part 1

Similar presentations


Presentation on theme: "Chapter 13 - Graphical User Interface Components: Part 1"— Presentation transcript:

1 Chapter 13 - Graphical User Interface Components: Part 1
Outline Introduction Overview of Swing Components JLabel Event Handling TextFields How Event Handling Works JButton JCheckBox and JRadioButton JComboBox JList Multiple-Selection Lists Mouse Event Handling Adapter Classes Key Event Handling

2 Chapter 13 - Graphical User Interface Components: Part 1
Outline Layout Managers FlowLayout BorderLayout GridLayout Panels (Optional Case Study) Thinking About Objects: Use Cases

3 Olay İşleme Olay: Kaynaktaki bir durum değişikliğini tarif eden nesnedir. Butona basmak,klavye ile karakter girme,fareyi tıklama... Olay Kaynakları Olay üreten nesne Olay Dinleyicileri Olay olduğunda haber verilen nesnedir. Java.awt.event  olayları alan ve işleyen metotların bulunduğu paket.

4 java.awt.event Paketindeki Ana Olay Sınıfları
Açıklama AdjustmentEvent Kaydırma çubuğu yönlendirildiğinde üretilir. ComponentEvent Bir bileşen gizlendiğinde, taşındığında, boyutu değiştirildiğinde yada görünür hale geldiğinde üretilir. ContainerEvent Bir bileşen, bir konteynere eklenince yada ondan çıkarılınca üretilir. FocusEvent Bir bileşen kalvye odağı kazandığında yada kaybettiğinde üretilir. InputEvent Bileşen girdi olay sısnfları için bir üst sınıfı soyutlar ItemEvent Onay kutusu yada liste öğesi tıklandığında yada bir seçim işi onaylandığında yada bir menü seçildiğinde üretilir. KeyEvent Klavyeden bir girdi alındığında üretilir. MouseEvent Fare sürüklendiğinde,taşındığında,tıklandığında,basıldığında, yada bırakıldığında üretilir TextEvent Bir metin alanının yada sahasının değeri değiştiğinde üretilir. WindowEvent Bir pencere, etkinleştiğinde, kapandığında, etkinsizleştiğinde, simgeleştirildiğinde... Üretilir. ActionEvent Bir düğmeye basıldığında, bir liste öğesi iki kere tıklandığında, yada bir menü öğesi seçildiğinde

5 Olay Kaynakları Button CheckBox Choice List Menu Item Scrollbar Metin
Window

6 Olay Dinleyicileri Arabirimleri
ActionListener void actionPerformed(ActionEvent e) AdjustmentListener void adjustmentValueChanged(AdjustmentEvent e) ComponentListener void componentResized(ComponentEvent e) void componentMoved(ComponentEvent e) void componentShown(ComponentEvent e) void componentHidden(ComponentEvent e) ContainerListener void componentAdded(ContainerEvent e) void componentRemoved(ContainerEvent e)

7 Olay Dinleyicileri Arabirimleri
FocusListener void focusGained(FocusEvent e) void focusLost(FocusEvent e) ItemListener void itemStateChanged(ItemEvent e) KeyListener void keyPressed(KeyEvent e) void keyReleased(KeyEvent e) void keyTyped(KeyEvent e) MouseListener void mouseClicked(MouseEvent e) void mouseEntered(MouseEvent e) void mouseExited(MouseEvent e) void mousePressed(MouseEvent e) void mouseReleased(MouseEvent e)

8 Olay Dinleyicileri Arabirimleri
MouseMotionListener void mouseDragged(MouseEvent e) void mouseMoved(MouseEvent e) TextListener void textChanged(TextEvent e) WindowListener void windowActivated(WindowEvent e) void windowClosed(WindowEvent e) void windowDeactivated(WindowEvent e) void windowDeiconified(WindowEvent e) void windowIconified(WindowEvent e) void windowOpened(WindowEvent e)

9 Fig. 13.2 Some basic GUI components

10 13.2 Overview of Swing Components
Swing GUI components Package javax.swing Components originate from AWT (package java.awt) Contain look and feel Appearance and how users interact with program Lightweight components Written completely in Java

11 13.2 Overview of Swing Components
Class Component Contains method paint for drawing Component onscreen Class Container Collection of related components Contains method add for adding components Class JComponent Pluggable look and feel for customizing look and feel Shortcut keys (mnemonics) Common event-handling capabilities

12 Fig. 13.3 Common superclasses of many of the Swing components
Object Object Component Component Container Container JComponent JComponent

13 Label 13.3 JLabel Provide text on GUI Defined with class JLabel
Can display: Single line of read-only text Image Text and image

14 LabelTest.java Line 8 Line 20 Line 21
// Fig. 13.4: LabelTest.java // Demonstrating the JLabel class. import java.awt.*; import java.awt.event.*; import javax.swing.*; 6 public class LabelTest extends JFrame { private JLabel label1, label2, label3; 9 // set up GUI public LabelTest() { super( "Testing JLabel" ); 14 // get content pane and set its layout Container container = getContentPane(); container.setLayout( new FlowLayout() ); 18 // JLabel constructor with a string argument label1 = new JLabel( "Label with text" ); label1.setToolTipText( "This is label1" ); container.add( label1 ); 23 LabelTest.java Line 8 Line 20 Line 21 Declare three JLabels Create first JLabel with text “Label with text” Tool tip is text that appears when user moves cursor over JLabel

15 LabelTest.java Lines 16-17 Lines 32-37
// JLabel constructor with string, Icon and alignment arguments Icon bug = new ImageIcon( "bug1.gif" ); label2 = new JLabel( "Label with text and icon", bug, SwingConstants.LEFT ); label2.setToolTipText( "This is label2" ); container.add( label2 ); 30 // JLabel constructor no arguments label3 = new JLabel(); label3.setText( "Label with icon and text at bottom" ); label3.setIcon( bug ); label3.setHorizontalTextPosition( SwingConstants.CENTER ); label3.setVerticalTextPosition( SwingConstants.BOTTOM ); label3.setToolTipText( "This is label3" ); container.add( label3 ); 39 setSize( 275, 170 ); setVisible( true ); 42 } // end constructor 44 public static void main( String args[] ) { LabelTest application = new LabelTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } Create second JLabel with text to left of image LabelTest.java Lines Lines 32-37 Create third JLabel with text below image

16 50 51 } // end class LabelTest
LabelTest.java

17 13.4 Event Handling GUIs are event driven
Generate events when user interacts with GUI e.g., moving mouse, pressing button, typing in text field, etc. Class java.awt.AWTEvent

18 Fig. 13.5 Some event classes of package java.awt.event
Object EventObject AWTEvent ActionEvent AdjustmentEvent ItemEvent TextEvent ContainerEvent FocusEvent PaintEvent WindowEvent InputEvent MouseWheelEvent ComponentEvent KeyEvent MouseEvent Object ActionEvent EventObject AdjustmentEvent AWTEvent ContainerEvent ItemEvent FocusEvent TextEvent PaintEvent ComponentEvent WindowEvent InputEvent KeyEvent MouseEvent MouseWheelEvent

19 13.4 Event Handling Event-handling model Three parts
Event source GUI component with which user interacts Event object Encapsulates information about event that occurred Event listener Receives event object when notified, then responds Programmer must perform two tasks Register event listener for event source Implement event-handling method (event handler)

20 Fig. 13.6 Event-listener interfaces of package java.awt.event
ActionListener AdjustmentListener ComponentListener ContainerListener FocusListener ItemListener KeyListener MouseListener MouseMotionListener TextListener WindowListener «interface» EventListener «interface» ActionListener «interface» AdjustmentListener «interface» ComponentListener «interface» ContainerListener «interface» FocusListener «interface» ItemListener «interface» KeyListener «interface» MouseListener «interface» MouseMotionListener «interface» TextListener

21 13.5 TextFields JTextField JPasswordField
Single-line area in which user can enter text JPasswordField Extends JTextField Hides characters that user enters

22 TextFieldTest.java Lines 8-9 Line 20 Line 24
// Fig. 13.7: TextFieldTest.java // Demonstrating the JTextField class. import java.awt.*; import java.awt.event.*; import javax.swing.*; 6 public class TextFieldTest extends JFrame { private JTextField textField1, textField2, textField3; private JPasswordField passwordField; 10 // set up GUI public TextFieldTest() { super( "Testing JTextField and JPasswordField" ); 15 Container container = getContentPane(); container.setLayout( new FlowLayout() ); 18 // construct textfield with default sizing textField1 = new JTextField( 10 ); container.add( textField1 ); 22 // construct textfield with default text textField2 = new JTextField( "Enter text here" ); container.add( textField2 ); 26 TextFieldTest.java Lines 8-9 Line 20 Line 24 Declare three JTextFields and one JPasswordField First JTextField contains empty string Second JTextField contains text “Enter text here”

23 TextFieldTest.java Line 30 Line 34 Lines 39-42
// construct textfield with default text, // 20 visible elements and no event handler textField3 = new JTextField( "Uneditable text field", 20 ); textField3.setEditable( false ); container.add( textField3 ); 32 // construct passwordfield with default text passwordField = new JPasswordField( "Hidden text" ); container.add( passwordField ); 36 // register event handlers TextFieldHandler handler = new TextFieldHandler(); textField1.addActionListener( handler ); textField2.addActionListener( handler ); textField3.addActionListener( handler ); passwordField.addActionListener( handler ); 43 setSize( 325, 100 ); setVisible( true ); 46 } // end constructor TextFieldTest 48 public static void main( String args[] ) { TextFieldTest application = new TextFieldTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } Third JTextField contains uneditable text TextFieldTest.java Line 30 Line 34 Lines 39-42 JPasswordField contains text “Hidden text,” but text appears as series of asterisks (*) Register GUI components with TextFieldHandler (register for ActionEvents)

24 TextFieldTest.java Line 56 Line 59
54 // private inner class for event handling private class TextFieldHandler implements ActionListener { 57 // process textfield events public void actionPerformed( ActionEvent event ) { String string = ""; 62 // user pressed Enter in JTextField textField1 if ( event.getSource() == textField1 ) string = "textField1: " + event.getActionCommand(); 66 // user pressed Enter in JTextField textField2 else if ( event.getSource() == textField2 ) string = "textField2: " + event.getActionCommand(); 70 // user pressed Enter in JTextField textField3 else if ( event.getSource() == textField3 ) string = "textField3: " + event.getActionCommand(); 74 // user pressed Enter in JTextField passwordField else if ( event.getSource() == passwordField ) { string = "passwordField: " + new String( passwordField.getPassword() ); } Every TextFieldHandler instance is an ActionListener TextFieldTest.java Line 56 Line 59 Method actionPerformed invoked when user presses Enter in GUI field

25 80 JOptionPane.showMessageDialog( null, string ); 82 } // end method actionPerformed 84 } // end private inner class TextFieldHandler 86 87 } // end class TextFieldTest TextFieldTest.java

26 TextFieldTest.java

27 13.6 How Event Handling Works
Two open questions from Section 13.4 How did event handler get registered? Answer: Through component’s method addActionListener Lines of TextFieldTest.java How does component know to call actionPerformed? Event is dispatched only to listeners of appropriate type Each event type has corresponding event-listener interface Event ID specifies event type that occurred

28 Fig. 13.8 Event registration for JTextField textField1
listenerList ... handler This reference is created by the statement textField1.addActionListener( handler ); public void actionPerformed( ActionEvent event ) { // event handled here } JTextField object TextFieldHandler object

29 13.7 JButton Button Component user clicks to trigger a specific action
Several different types Command buttons Check boxes Toggle buttons Radio buttons javax.swing.AbstractButton subclasses Command buttons are created with class JButton Generate ActionEvents when user clicks button

30 Fig. 13.9 Swing button hierarchy
JComponent AbstractButton JToggleButton JRadioButton JCheckBox JButton JComponent AbstractButton JButton JToggleButton JCheckBox JRadioButton

31 ButtonTest.java Line 8 Line 20 Lines 24-26
// Fig : ButtonTest.java // Creating JButtons. import java.awt.*; import java.awt.event.*; import javax.swing.*; 6 public class ButtonTest extends JFrame { private JButton plainButton, fancyButton; 9 // set up GUI public ButtonTest() { super( "Testing Buttons" ); 14 // get content pane and set its layout Container container = getContentPane(); container.setLayout( new FlowLayout() ); 18 // create buttons plainButton = new JButton( "Plain Button" ); container.add( plainButton ); 22 Icon bug1 = new ImageIcon( "bug1.gif" ); Icon bug2 = new ImageIcon( "bug2.gif" ); fancyButton = new JButton( "Fancy Button", bug1 ); fancyButton.setRolloverIcon( bug2 ); container.add( fancyButton ); ButtonTest.java Line 8 Line 20 Lines 24-26 Create two references to JButton instances Instantiate JButton with text Instantiate JButton with image and rollover image

32 ButtonTest.java Line 31 Lines 32-33 Line 50
28 // create an instance of inner class ButtonHandler // to use for button event handling ButtonHandler handler = new ButtonHandler(); fancyButton.addActionListener( handler ); plainButton.addActionListener( handler ); 34 setSize( 275, 100 ); setVisible( true ); 37 } // end ButtonTest constructor 39 public static void main( String args[] ) { ButtonTest application = new ButtonTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 45 // inner class for button event handling private class ButtonHandler implements ActionListener { 48 // handle button event public void actionPerformed( ActionEvent event ) { JOptionPane.showMessageDialog( ButtonTest.this, "You pressed: " + event.getActionCommand() ); } Instantiate ButtonHandler for JButton event handling ButtonTest.java Line 31 Lines Line 50 Register JButtons to receive events from ButtonHandler When user clicks JButton, ButtonHandler invokes method actionPerformed of all registered listeners

33 ButtonTest.java 55 56 } // end private inner class ButtonHandler 57
58 } // end class ButtonTest ButtonTest.java

34 13.8 JCheckBox and JRadioButton
State buttons On/Off or true/false values Java provides three types JToggleButton JCheckBox JRadioButton

35 CheckBoxTest.java Line 9 Line 22
// Fig : CheckBoxTest.java // Creating JCheckBox buttons. import java.awt.*; import java.awt.event.*; import javax.swing.*; 6 public class CheckBoxTest extends JFrame { private JTextField field; private JCheckBox bold, italic; 10 // set up GUI public CheckBoxTest() { super( "JCheckBox Test" ); 15 // get content pane and set its layout Container container = getContentPane(); container.setLayout( new FlowLayout() ); 19 // set up JTextField and set its font field = new JTextField( "Watch the font style change", 20 ); field.setFont( new Font( "Serif", Font.PLAIN, 14 ) ); container.add( field ); 24 CheckBoxTest.java Line 9 Line 22 Declare two JCheckBox instances Set JTextField font to Serif, 14-point plain

36 CheckBoxTest.java Lines 26 and 29 Lines 34-35
// create checkbox objects bold = new JCheckBox( "Bold" ); container.add( bold ); 28 italic = new JCheckBox( "Italic" ); container.add( italic ); 31 // register listeners for JCheckBoxes CheckBoxHandler handler = new CheckBoxHandler(); bold.addItemListener( handler ); italic.addItemListener( handler ); 36 setSize( 275, 100 ); setVisible( true ); 39 } // end CheckBoxText constructor 41 public static void main( String args[] ) { CheckBoxTest application = new CheckBoxTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 47 Instantiate JCheckBoxs for bolding and italicizing JTextField text, respectively CheckBoxTest.java Lines 26 and 29 Lines 34-35 Register JCheckBoxs to receive events from CheckBoxHandler

37 CheckBoxTest.java Line 54 Line 65
// private inner class for ItemListener event handling private class CheckBoxHandler implements ItemListener { private int valBold = Font.PLAIN; private int valItalic = Font.PLAIN; 52 // respond to checkbox events public void itemStateChanged( ItemEvent event ) { // process bold checkbox events if ( event.getSource() == bold ) valBold = bold.isSelected() ? Font.BOLD : Font.PLAIN; 59 // process italic checkbox events if ( event.getSource() == italic ) valItalic = italic.isSelected() ? Font.ITALIC : Font.PLAIN; 63 // set text field font field.setFont( new Font( "Serif", valBold + valItalic, 14 ) ); 66 } // end method itemStateChanged 68 } // end private inner class CheckBoxHandler 70 71 } // end class CheckBoxTest When user selects JCheckBox, CheckBoxHandler invokes method itemStateChanges of all registered listeners CheckBoxTest.java Line 54 Line 65 Change JTextField font, depending on which JCheckBox was selected

38 CheckBoxTest.java

39 RadioButtonTest.java Lines 10-11 Line 12
// Fig : RadioButtonTest.java // Creating radio buttons using ButtonGroup and JRadioButton. import java.awt.*; import java.awt.event.*; import javax.swing.*; 6 public class RadioButtonTest extends JFrame { private JTextField field; private Font plainFont, boldFont, italicFont, boldItalicFont; private JRadioButton plainButton, boldButton, italicButton, boldItalicButton; private ButtonGroup radioGroup; 13 // create GUI and fonts public RadioButtonTest() { super( "RadioButton Test" ); 18 // get content pane and set its layout Container container = getContentPane(); container.setLayout( new FlowLayout() ); 22 // set up JTextField field = new JTextField( "Watch the font style change", 25 ); container.add( field ); 26 RadioButtonTest.java Lines Line 12 Declare four JRadioButton instances JRadioButtons normally appear as a ButtonGroup

40 RadioButtonTest.java Lines 28-35 Lines 41-45
// create radio buttons plainButton = new JRadioButton( "Plain", true ); container.add( plainButton ); 30 boldButton = new JRadioButton( "Bold", false ); container.add( boldButton ); 33 italicButton = new JRadioButton( "Italic", false ); container.add( italicButton ); 36 boldItalicButton = new JRadioButton( "Bold/Italic", false ); container.add( boldItalicButton ); 39 // create logical relationship between JRadioButtons radioGroup = new ButtonGroup(); radioGroup.add( plainButton ); radioGroup.add( boldButton ); radioGroup.add( italicButton ); radioGroup.add( boldItalicButton ); 46 // create font objects plainFont = new Font( "Serif", Font.PLAIN, 14 ); boldFont = new Font( "Serif", Font.BOLD, 14 ); italicFont = new Font( "Serif", Font.ITALIC, 14 ); boldItalicFont = new Font( "Serif", Font.BOLD + Font.ITALIC, 14 ); field.setFont( plainFont ); // set initial font 53 Instantiate JRadioButtons for manipulating JTextField text font RadioButtonTest.java Lines Lines 41-45 JRadioButtons belong to ButtonGroup

41 RadioButtonTest.java Lines 55-60
// register events for JRadioButtons plainButton.addItemListener( new RadioButtonHandler( plainFont ) ); boldButton.addItemListener( new RadioButtonHandler( boldFont ) ); italicButton.addItemListener( new RadioButtonHandler( italicFont ) ); boldItalicButton.addItemListener( new RadioButtonHandler( boldItalicFont ) ); 61 setSize( 300, 100 ); setVisible( true ); 64 } // end RadioButtonTest constructor 66 public static void main( String args[] ) { RadioButtonTest application = new RadioButtonTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 72 // private inner class to handle radio button events private class RadioButtonHandler implements ItemListener { private Font font; 76 public RadioButtonHandler( Font f ) { font = f; } Register JRadioButtons to receive events from RadioButtonHandler RadioButtonTest.java Lines 55-60

42 RadioButtonTest.java Line 83 Line 85
81 // handle radio button events public void itemStateChanged( ItemEvent event ) { field.setFont( font ); } 87 } // end private inner class RadioButtonHandler 89 90 } // end class RadioButtonTest When user selects JRadioButton, RadioButtonHandler invokes method itemStateChanged of all registered listeners RadioButtonTest.java Line 83 Line 85 Set font corresponding to JRadioButton selected

43 13.9 JComboBox JComboBox List of items from which user can select
Also called a drop-down list

44 ComboBoxTest.java 1 // Fig. 13.13: ComboBoxTest.java
// Using a JComboBox to select an image to display. import java.awt.*; import java.awt.event.*; import javax.swing.*; 6 public class ComboBoxTest extends JFrame { private JComboBox imagesComboBox; private JLabel label; 10 private String names[] = { "bug1.gif", "bug2.gif", "travelbug.gif", "buganim.gif" }; private Icon icons[] = { new ImageIcon( names[ 0 ] ), new ImageIcon( names[ 1 ] ), new ImageIcon( names[ 2 ] ), new ImageIcon( names[ 3 ] ) }; 16 // set up GUI public ComboBoxTest() { super( "Testing JComboBox" ); 21 // get content pane and set its layout Container container = getContentPane(); container.setLayout( new FlowLayout() ); 25 ComboBoxTest.java

45 ComboBoxTest.java Lines 27-28 Line 29 Line 34 Lines 38-39
// set up JComboBox and register its event handler imagesComboBox = new JComboBox( names ); imagesComboBox.setMaximumRowCount( 3 ); imagesComboBox.addItemListener( 30 new ItemListener() { // anonymous inner class 32 // handle JComboBox event public void itemStateChanged( ItemEvent event ) { // determine whether check box selected if ( event.getStateChange() == ItemEvent.SELECTED ) label.setIcon( icons[ imagesComboBox.getSelectedIndex() ] ); } 41 } // end anonymous inner class 43 ); // end call to addItemListener 45 container.add( imagesComboBox ); 47 // set up JLabel to display ImageIcons label = new JLabel( icons[ 0 ] ); container.add( label ); 51 Instantiate JComboBox to show three Strings from names array at a time ComboBoxTest.java Lines Line 29 Line 34 Lines 38-39 Register JComboBox to receive events from anonymous ItemListener When user selects item in JComboBox, ItemListener invokes method itemStateChanged of all registered listeners Set appropriate Icon depending on user selection

46 ComboBoxTest.java 52 setSize( 350, 100 ); 53 setVisible( true ); 54
} // end ComboBoxTest constructor 56 public static void main( String args[] ) { ComboBoxTest application = new ComboBoxTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 62 63 } // end class ComboBoxTest ComboBoxTest.java

47 13.10 JList List Series of items user can select one or more items
Single-selection vs. multiple-selection JList

48 ListTest.java 1 // Fig. 13.14: ListTest.java
// Selecting colors from a JList. import java.awt.*; import javax.swing.*; import javax.swing.event.*; 6 public class ListTest extends JFrame { private JList colorList; private Container container; 10 private final String colorNames[] = { "Black", "Blue", "Cyan", "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", "Orange", "Pink", "Red", "White", "Yellow" }; 14 private final Color colors[] = { Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE, Color.YELLOW }; 19 // set up GUI public ListTest() { super( "List Test" ); 24 // get content pane and set its layout container = getContentPane(); container.setLayout( new FlowLayout() ); ListTest.java

49 ListTest.java Line 30 Line 34 Line 38 Line 43 Lines 45-46
28 // create a list with items in colorNames array colorList = new JList( colorNames ); colorList.setVisibleRowCount( 5 ); 32 // do not allow multiple selections colorList.setSelectionMode( ListSelectionModel.SINGLE_SELECTION ); 35 // add a JScrollPane containing JList to content pane container.add( new JScrollPane( colorList ) ); colorList.addListSelectionListener( 39 new ListSelectionListener() { // anonymous inner class 41 // handle list selection events public void valueChanged( ListSelectionEvent event ) { container.setBackground( colors[ colorList.getSelectedIndex() ] ); } 48 } // end anonymous inner class 50 ); // end call to addListSelectionListener 52 Use colorNames array to populate JList ListTest.java Line 30 Line 34 Line 38 Line 43 Lines 45-46 JList allows single selections Register JList to receive events from anonymous ListSelectionListener When user selects item in JList, ListSelectionListener invokes method valueChanged of all registered listeners Set appropriate background depending on user selection

50 ListTest.java 53 setSize( 350, 150 ); 54 setVisible( true ); 55
} // end ListTest constructor 57 public static void main( String args[] ) { ListTest application = new ListTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 63 64 } // end class ListTest ListTest.java

51 13.11 Multiple-Selection Lists
Select many items from Jlist Allows continuous range selection

52 MultipleSelectionTest.java Lines 10-12 and 24 Lines 26-27
// Fig : MultipleSelectionTest.java // Copying items from one List to another. import java.awt.*; import java.awt.event.*; import javax.swing.*; 6 public class MultipleSelectionTest extends JFrame { private JList colorList, copyList; private JButton copyButton; private final String colorNames[] = { "Black", "Blue", "Cyan", "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", "Orange", "Pink", "Red", "White", "Yellow" }; 13 // set up GUI public MultipleSelectionTest() { super( "Multiple Selection Lists" ); 18 // get content pane and set its layout Container container = getContentPane(); container.setLayout( new FlowLayout() ); 22 // set up JList colorList colorList = new JList( colorNames ); colorList.setVisibleRowCount( 5 ); colorList.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION ); container.add( new JScrollPane( colorList ) ); MultipleSelectionTest.java Lines and 24 Lines 26-27 Use colorNames array to populate JList JList colorList allows multiple selections

53 MultipleSelectionTest.java Line 40 Lines 54-55
29 // create copy button and register its listener copyButton = new JButton( "Copy >>>" ); copyButton.addActionListener( 33 new ActionListener() { // anonymous inner class 35 // handle button event public void actionPerformed( ActionEvent event ) { // place selected values in copyList copyList.setListData( colorList.getSelectedValues() ); } 42 } // end anonymous inner class 44 ); // end call to addActionListener 46 container.add( copyButton ); 48 // set up JList copyList copyList = new JList( ); copyList.setVisibleRowCount( 5 ); copyList.setFixedCellWidth( 100 ); copyList.setFixedCellHeight( 15 ); copyList.setSelectionMode( ListSelectionModel.SINGLE_INTERVAL_SELECTION ); container.add( new JScrollPane( copyList ) ); MultipleSelectionTest.java Line 40 Lines 54-55 When user presses JButton, JList copyList adds items that user selected from JList colorList JList colorList allows single selections

54 MultipleSelectionTest.java 57 58 setSize( 300, 130 );
setVisible( true ); 60 } // end constructor MultipleSelectionTest 62 public static void main( String args[] ) { MultipleSelectionTest application = new MultipleSelectionTest(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 68 69 } // end class MultipleSelectionTest MultipleSelectionTest.java

55 Event-listener interfaces for mouse events
Mouse Event Handling Event-listener interfaces for mouse events MouseListener MouseMotionListener Listen for MouseEvents

56 Fig. 13.16 MouseListener and MouseMotionListener interface methods

57 MouseTracker.java Lines 20-21
// Fig : MouseTracker.java // Demonstrating mouse events. import java.awt.*; import java.awt.event.*; import javax.swing.*; 6 public class MouseTracker extends JFrame implements MouseListener, MouseMotionListener { 9 private JLabel statusBar; 11 // set up GUI and register mouse event handlers public MouseTracker() { super( "Demonstrating Mouse Events" ); 16 statusBar = new JLabel(); getContentPane().add( statusBar, BorderLayout.SOUTH ); 19 addMouseListener( this ); // listens for own mouse and addMouseMotionListener( this ); // mouse-motion events 22 setSize( 275, 100 ); setVisible( true ); } 26 MouseTracker.java Lines 20-21 Register JFrame to receive mouse events

58 MouseTracker.java Line 29 Line 36 Line 43 Line 50
// MouseListener event handlers // handle event when mouse released immediately after press public void mouseClicked( MouseEvent event ) { statusBar.setText( "Clicked at [" + event.getX() + ", " + event.getY() + "]" ); } 34 // handle event when mouse pressed public void mousePressed( MouseEvent event ) { statusBar.setText( "Pressed at [" + event.getX() + ", " + event.getY() + "]" ); } 41 // handle event when mouse released after dragging public void mouseReleased( MouseEvent event ) { statusBar.setText( "Released at [" + event.getX() + ", " + event.getY() + "]" ); } 48 // handle event when mouse enters area public void mouseEntered( MouseEvent event ) { Invoked when user presses and releases mouse button MouseTracker.java Line 29 Line 36 Line 43 Line 50 Invoked when user presses mouse button Invoked when user releases mouse button after dragging mouse Invoked when mouse cursor enters JFrame

59 MouseTracker.java Line 58 Line 66 Line 73
statusBar.setText( "Mouse entered at [" + event.getX() + ", " + event.getY() + "]" ); getContentPane().setBackground( Color.GREEN ); } 56 // handle event when mouse exits area public void mouseExited( MouseEvent event ) { statusBar.setText( "Mouse outside window" ); getContentPane().setBackground( Color.WHITE ); } 63 // MouseMotionListener event handlers // handle event when user drags mouse with button pressed public void mouseDragged( MouseEvent event ) { statusBar.setText( "Dragged at [" + event.getX() + ", " + event.getY() + "]" ); } 71 // handle event when user moves mouse public void mouseMoved( MouseEvent event ) { statusBar.setText( "Moved at [" + event.getX() + ", " + event.getY() + "]" ); } 78 MouseTracker.java Line 58 Line 66 Line 73 Invoked when mouse cursor exits JFrame Invoked when user drags mouse cursor Invoked when user moves mouse cursor

60 MouseTracker.java 79 public static void main( String args[] ) 80 {
{ MouseTracker application = new MouseTracker(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 84 85 } // end class MouseTracker MouseTracker.java

61 13.13 Adapter Classes Adapter class Implements interface
Provides default implementation of each interface method Used when all methods in interface is not needed

62 Fig. 13.18 Event-adapter classes and the interfaces they implement in package java.awt.event

63 // Fig : Painter.java // Using class MouseMotionAdapter. import java.awt.*; import java.awt.event.*; import javax.swing.*; 6 public class Painter extends JFrame { private int pointCount = 0; 9 // array of 1000 java.awt.Point references private Point points[] = new Point[ 1000 ]; 12 // set up GUI and register mouse event handler public Painter() { super( "A simple paint program" ); 17 // create a label and place it in SOUTH of BorderLayout getContentPane().add( new JLabel( "Drag the mouse to draw" ), BorderLayout.SOUTH ); 21 addMouseMotionListener( 23 new MouseMotionAdapter() { // anonymous inner class 25 Painter.java Line 22 Register MouseMotionListener to listen for window’s mouse-motion events

64 Painter.java Line 27 Line 30 Line 51
// store drag coordinates and repaint public void mouseDragged( MouseEvent event ) { if ( pointCount < points.length ) { points[ pointCount ] = event.getPoint(); pointCount; repaint(); } } 35 } // end anonymous inner class 37 ); // end call to addMouseMotionListener 39 setSize( 300, 150 ); setVisible( true ); 42 } // end Painter constructor 44 // draw oval in a 4-by-4 bounding box at specified location on window public void paint( Graphics g ) { super.paint( g ); // clears drawing area 49 for ( int i = 0; i < points.length && points[ i ] != null; i++ ) g.fillOval( points[ i ].x, points[ i ].y, 4, 4 ); } Override method mouseDragged, but not method mouseMoved Painter.java Line 27 Line 30 Line 51 Store coordinates where mouse was dragged, then repaint JFrame Draw circle of diameter 4 where user dragged cursor

65 Painter.java 53 54 public static void main( String args[] ) 55 {
{ Painter application = new Painter(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 59 60 } // end class Painter Painter.java

66 MouseDetails.java Line 15
// Fig : MouseDetails.java // Demonstrating mouse clicks and distinguishing between mouse buttons. import java.awt.*; import java.awt.event.*; import javax.swing.*; 6 public class MouseDetails extends JFrame { private int xPos, yPos; 9 // set title bar String; register mouse listener; size and show window public MouseDetails() { super( "Mouse clicks and buttons" ); 14 addMouseListener( new MouseClickHandler() ); 16 setSize( 350, 150 ); setVisible( true ); } 20 // draw String at location where mouse was clicked public void paint( Graphics g ) { // call superclass paint method super.paint( g ); 26 MouseDetails.java Line 15 Register mouse listener

67 MouseDetails.java Line 41 Lines 43-44 Line 46 Line 48 Line 51
g.drawString( [" + xPos + ", " + yPos + "]", xPos, yPos ); } 30 public static void main( String args[] ) { MouseDetails application = new MouseDetails(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 36 // inner class to handle mouse events private class MouseClickHandler extends MouseAdapter { 39 // handle mouse click event and determine which button was pressed public void mouseClicked( MouseEvent event ) { xPos = event.getX(); yPos = event.getY(); 45 String title = "Clicked " + event.getClickCount() + " time(s)"; 47 if ( event.isMetaDown() ) // right mouse button title += " with right mouse button"; 50 else if ( event.isAltDown() ) // middle mouse button title += " with center mouse button"; MouseDetails.java Line 41 Lines Line 46 Line 48 Line 51 Invoke method mouseClicked when user clicks mouse Store mouse-cursor coordinates where mouse was clicked Determine number of times user has clicked mouse Determine if user clicked right mouse button Determine if user clicked middle mouse button

68 MouseDetails.java 53 54 else // left mouse button
title += " with left mouse button"; 56 setTitle( title ); // set title bar of window repaint(); 59 } // end method mouseClicked 61 } // end private inner class MouseClickHandler 63 64 } // end class MouseDetails MouseDetails.java

69 Fig InputEvent methods that help distinguish among left-, center- and right-mouse-button clicks

70 Interface KeyListener
Key Event Handling Interface KeyListener Handles key events Generated when keys on keyboard are pressed and released KeyEvent Contains virtual key code that represents key

71 Register JFrame for key events
// Fig : KeyDemo.java // Demonstrating keystroke events. import java.awt.*; import java.awt.event.*; import javax.swing.*; 6 public class KeyDemo extends JFrame implements KeyListener { private String line1 = "", line2 = "", line3 = ""; private JTextArea textArea; 10 // set up GUI public KeyDemo() { super( "Demonstrating Keystroke Events" ); 15 // set up JTextArea textArea = new JTextArea( 10, 15 ); textArea.setText( "Press any key on the keyboard..." ); textArea.setEnabled( false ); textArea.setDisabledTextColor( Color.BLACK ); getContentPane().add( textArea ); 22 addKeyListener( this ); // allow frame to process Key events 24 setSize( 350, 100 ); setVisible( true ); KeyDemo.java Line 23 Register JFrame for key events

72 KeyDemo.java Line 31 Line 33 and 40 Line 38 Line 45
27 } // end KeyDemo constructor 29 // handle press of any key public void keyPressed( KeyEvent event ) { line1 = "Key pressed: " + event.getKeyText( event.getKeyCode() ); setLines2and3( event ); } 36 // handle release of any key public void keyReleased( KeyEvent event ) { line1 = "Key released: " + event.getKeyText( event.getKeyCode() ); setLines2and3( event ); } 43 // handle press of an action key public void keyTyped( KeyEvent event ) { line1 = "Key typed: " + event.getKeyChar(); setLines2and3( event ); } 50 // set second and third lines of output private void setLines2and3( KeyEvent event ) { KeyDemo.java Line 31 Line 33 and 40 Line 38 Line 45 Called when user presses key Return virtual key code Called when user releases key Called when user types key

73 Determine if modifier keys (e.g., Alt, Ctrl, Meta and Shift) were used
line2 = "This key is " + ( event.isActionKey() ? "" : "not " ) + "an action key"; 56 String temp = event.getKeyModifiersText( event.getModifiers() ); 58 line3 = "Modifier keys pressed: " + ( temp.equals( "" ) ? "none" : temp ); 61 textArea.setText( line1 + "\n" + line2 + "\n" + line3 + "\n" ); } 64 public static void main( String args[] ) { KeyDemo application = new KeyDemo(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 70 71 } // end class KeyDemo KeyDemo.java Line 57 Determine if modifier keys (e.g., Alt, Ctrl, Meta and Shift) were used

74 KeyDemo.java

75 13.15 Layout Managers Layout managers
Provided for arranging GUI components Provide basic layout capabilities Processes layout details Programmer can concentrate on basic “look and feel” Interface LayoutManager

76 Fig Layout managers

77 13.15.1 FlowLayout FlowLayout Most basic layout manager
GUI components placed in container from left to right

78 FlowLayoutDemo.java Lines 17 and 21
// Fig : FlowLayoutDemo.java // Demonstrating FlowLayout alignments. import java.awt.*; import java.awt.event.*; import javax.swing.*; 6 public class FlowLayoutDemo extends JFrame { private JButton leftButton, centerButton, rightButton; private Container container; private FlowLayout layout; 11 // set up GUI and register button listeners public FlowLayoutDemo() { super( "FlowLayout Demo" ); 16 layout = new FlowLayout(); 18 // get content pane and set its layout container = getContentPane(); container.setLayout( layout ); 22 // set up leftButton and register listener leftButton = new JButton( "Left" ); container.add( leftButton ); FlowLayoutDemo.java Lines 17 and 21 Set layout as FlowLayout

79 FlowLayoutDemo.java Line 33 Line 53
leftButton.addActionListener( 27 new ActionListener() { // anonymous inner class 29 // process leftButton event public void actionPerformed( ActionEvent event ) { layout.setAlignment( FlowLayout.LEFT ); 34 // realign attached components layout.layoutContainer( container ); } 38 } // end anonymous inner class 40 ); // end call to addActionListener 42 // set up centerButton and register listener centerButton = new JButton( "Center" ); container.add( centerButton ); centerButton.addActionListener( 47 new ActionListener() { // anonymous inner class 49 // process centerButton event public void actionPerformed( ActionEvent event ) { layout.setAlignment( FlowLayout.CENTER ); 54 FlowLayoutDemo.java Line 33 Line 53 When user presses left JButton, left align components When user presses center JButton, center components

80 FlowLayoutDemo.java Line 71
// realign attached components layout.layoutContainer( container ); } } ); 60 // set up rightButton and register listener rightButton = new JButton( "Right" ); container.add( rightButton ); rightButton.addActionListener( 65 new ActionListener() { // anonymous inner class 67 // process rightButton event public void actionPerformed( ActionEvent event ) { layout.setAlignment( FlowLayout.RIGHT ); 72 // realign attached components layout.layoutContainer( container ); } } ); 78 setSize( 300, 75 ); setVisible( true ); FlowLayoutDemo.java Line 71 When user presses right JButton, right components

81 FlowLayoutDemo.java 81 82 } // end constructor FlowLayoutDemo 83
public static void main( String args[] ) { FlowLayoutDemo application = new FlowLayoutDemo(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 89 90 } // end class FlowLayoutDemo FlowLayoutDemo.java

82 13.15.2 BorderLayout BorderLayout
Arranges components into five regions NORTH (top of container) SOUTH (bottom of container) EAST (left of container) WEST (right of container) CENTER (center of container)

83 BorderLayoutDemo.java Lines 18 and 22
// Fig : BorderLayoutDemo.java // Demonstrating BorderLayout. import java.awt.*; import java.awt.event.*; import javax.swing.*; 6 public class BorderLayoutDemo extends JFrame implements ActionListener { private JButton buttons[]; private final String names[] = { "Hide North", "Hide South", "Hide East", "Hide West", "Hide Center" }; private BorderLayout layout; 12 // set up GUI and event handling public BorderLayoutDemo() { super( "BorderLayout Demo" ); 17 layout = new BorderLayout( 5, 5 ); // 5 pixel gaps 19 // get content pane and set its layout Container container = getContentPane(); container.setLayout( layout ); 23 // instantiate button objects buttons = new JButton[ names.length ]; 26 BorderLayoutDemo.java Lines 18 and 22 Set layout as BorderLayout with 5-pixel horizontal and vertical gaps

84 BorderLayoutDemo.java Lines 33-37 Lines 50 and 52
for ( int count = 0; count < names.length; count++ ) { buttons[ count ] = new JButton( names[ count ] ); buttons[ count ].addActionListener( this ); } 31 // place buttons in BorderLayout; order not important container.add( buttons[ 0 ], BorderLayout.NORTH ); container.add( buttons[ 1 ], BorderLayout.SOUTH ); container.add( buttons[ 2 ], BorderLayout.EAST ); container.add( buttons[ 3 ], BorderLayout.WEST ); container.add( buttons[ 4 ], BorderLayout.CENTER ); 38 setSize( 300, 200 ); setVisible( true ); 41 } // end constructor BorderLayoutDemo 43 // handle button events public void actionPerformed( ActionEvent event ) { for ( int count = 0; count < buttons.length; count++ ) 48 if ( event.getSource() == buttons[ count ] ) buttons[ count ].setVisible( false ); else buttons[ count ].setVisible( true ); BorderLayoutDemo.java Lines Lines 50 and 52 Place JButtons in regions specified by BorderLayout When JButtons are “invisible,” they are not displayed on screen, and BorderLayout rearranges

85 BorderLayoutDemo.java 53 54 // re-layout the content pane
layout.layoutContainer( getContentPane() ); } 57 public static void main( String args[] ) { BorderLayoutDemo application = new BorderLayoutDemo(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 63 64 } // end class BorderLayoutDemo BorderLayoutDemo.java

86 BorderLayoutDemo.java

87 13.15.3 GridLayout GridLayout
Divides container into grid of specified row an columns Components are added starting at top-left cell Proceed left-to-fight until row is full

88 GridLayoutDemo.java Line 21 Line 22
// Fig : GridLayoutDemo.java // Demonstrating GridLayout. import java.awt.*; import java.awt.event.*; import javax.swing.*; 6 public class GridLayoutDemo extends JFrame implements ActionListener { private JButton buttons[]; private final String names[] = { "one", "two", "three", "four", "five", "six" }; private boolean toggle = true; private Container container; private GridLayout grid1, grid2; 14 // set up GUI public GridLayoutDemo() { super( "GridLayout Demo" ); 19 // set up layouts grid1 = new GridLayout( 2, 3, 5, 5 ); grid2 = new GridLayout( 3, 2 ); 23 // get content pane and set its layout container = getContentPane(); container.setLayout( grid1 ); GridLayoutDemo.java Line 21 Line 22 Create GridLayout grid1 with 2 rows and 3 columns Create GridLayout grid2 with 3 rows and 2 columns

89 GridLayoutDemo.java Lines 46 and 48
27 // create and add buttons buttons = new JButton[ names.length ]; 30 for ( int count = 0; count < names.length; count++ ) { buttons[ count ] = new JButton( names[ count ] ); buttons[ count ].addActionListener( this ); container.add( buttons[ count ] ); } 36 setSize( 300, 150 ); setVisible( true ); 39 } // end constructor GridLayoutDemo 41 // handle button events by toggling between layouts public void actionPerformed( ActionEvent event ) { if ( toggle ) container.setLayout( grid2 ); else container.setLayout( grid1 ); 49 toggle = !toggle; // set toggle to opposite value container.validate(); } GridLayoutDemo.java Lines 46 and 48 Toggle current GridLayout when user presses JButton

90 GridLayoutDemo.java 53 54 public static void main( String args[] )
{ GridLayoutDemo application = new GridLayoutDemo(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 59 60 } // end class GridLayoutDemo GridLayoutDemo.java

91 13.16 Panels Panel Helps organize components
Class JPanel is JComponent subclass May have components (and other panels) added to them

92 Create JPanel to hold JButtons
// Fig : PanelDemo.java // Using a JPanel to help lay out components. import java.awt.*; import java.awt.event.*; import javax.swing.*; 6 public class PanelDemo extends JFrame { private JPanel buttonPanel; private JButton buttons[]; 10 // set up GUI public PanelDemo() { super( "Panel Demo" ); 15 // get content pane Container container = getContentPane(); 18 // create buttons array buttons = new JButton[ 5 ]; 21 // set up panel and set its layout buttonPanel = new JPanel(); buttonPanel.setLayout( new GridLayout( 1, buttons.length ) ); 25 PanelDemo.java Line 23 Create JPanel to hold JButtons

93 PanelDemo.java Line 29 Line 32
// create and add buttons for ( int count = 0; count < buttons.length; count++ ) { buttons[ count ] = new JButton( "Button " + ( count + 1 ) ); buttonPanel.add( buttons[ count ] ); } 31 container.add( buttonPanel, BorderLayout.SOUTH ); 33 setSize( 425, 150 ); setVisible( true ); 36 } // end constructor PanelDemo 38 public static void main( String args[] ) { PanelDemo application = new PanelDemo(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 44 45 } // end class PanelDemo Add JButtons to JPanel PanelDemo.java Line 29 Line 32 Add JPanel to SOUTH region of Container

94 13.17 (Optional Case Study) Thinking About Objects: Use Cases
Represents capabilities that systems provide to clients Automated-teller-machine use cases “Deposit Money,” “Withdraw Money,” “Transfer Funds”

95 13.17 (Optional Case Study) Thinking About Objects: Use Cases
Use-case diagram Models use cases in system Facilitates system-requirements gathering Notation Stick figure represents actor Actor represents set of roles that external entity can play System box (rectangle) contains system use cases Ovals represent use cases

96 13.17 (Optional Case Study) Thinking About Objects: Use Cases
Elevator-simulation use cases “Create Person” From user’s perspective “Relocate Person” (move to other floor) From Person’s perspective Constructing GUI Use “Create Person” use case

97 Fig. 13.28 Use case diagram for elevator simulation from user’s perspective
Create Person User

98 Fig. 13.29 Use case diagram from the perspective of a Person
Relocate Person Person


Download ppt "Chapter 13 - Graphical User Interface Components: Part 1"

Similar presentations


Ads by Google