Presentation is loading. Please wait.

Presentation is loading. Please wait.

Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 13 Creating User Interfaces …Starry starry night flaming flowers that brightly blaze.

Similar presentations


Presentation on theme: "Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 13 Creating User Interfaces …Starry starry night flaming flowers that brightly blaze."— Presentation transcript:

1 Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 13 Creating User Interfaces …Starry starry night flaming flowers that brightly blaze swirling clouds in violet haze reflect in Vincent's eyes of China blue. Colors changing hue morning fields of amber grain weathered faces lined in pain are smoothed beneath the artist's loving hand. And now I understand what you tried to say to me and how you suffered for your sanity and how you tried to set them free….

2 Liang,Introduction to Java Programming,revised by Dai-kaiyu 2 Objectives To create graphical user interfaces with various user-interface components: JButton, JCheckBox, JRadioButton, JLabel, JTextField, JTextArea, JComboBox, JList, JScrollBar, and JSlider (§13.2 – 13.12). To create listeners for various types of events (§13.2 – 13.12). To use borders to visually group user-interface components (§13.2). To create image icons using the ImageIcon class (§13.3). To display multiple windows in an application (§13.13). To know how to create menu

3 Liang,Introduction to Java Programming,revised by Dai-kaiyu 3 Components Covered in the Chapter Introduces the frequently used GUI components Uses borders and icons

4 Liang,Introduction to Java Programming,revised by Dai-kaiyu 4

5 5 Borders You can set a border on any object of the JComponent class. Swing has several types of borders. To create a titled border, use new TitledBorder(String title). To create a line border, use new LineBorder(Color color, int width), where width specifies the thickness of the line. For example, the following code displays a titled border on a panel: JPanel panel = new JPanel(); panel.setBorder(new TitleBorder(“My Panel”));

6 Liang,Introduction to Java Programming,revised by Dai-kaiyu 6 Test Swing Common Features Component Properties font background foreground preferredSize minimumSize maximumSize JComponent Properties toolTipText border TestSwingCommonFeaturesRun

7 Liang,Introduction to Java Programming,revised by Dai-kaiyu 7 Buttons A button is a component that triggers an action event when clicked. Swing provides regular buttons, toggle buttons, check box buttons, and radio buttons. The common features of these buttons are represented in javax.swing.AbstractButton.

8 Liang,Introduction to Java Programming,revised by Dai-kaiyu 8

9 9 JButton JButton inherits AbstractButton and provides several constructors to create buttons.

10 Liang,Introduction to Java Programming,revised by Dai-kaiyu 10 JButton Constructors The following are JButton constructors: JButton() JButton(String text) JButton(String text, Icon icon) JButton(Icon icon)

11 Liang,Introduction to Java Programming,revised by Dai-kaiyu 11 JButton Properties text icon mnemonic horizontalAlignment verticalAlignment horizontalTextPosition verticalTextPosition iconTextGap

12 Liang,Introduction to Java Programming,revised by Dai-kaiyu 12 Icons An icon is a fixed-size picture; typically it is small and used to decorate components. javax.swing.Icon is an interface. To create an image, use its concrete class javax.swing.ImageIcon. For example, the following statement creates an icon from an image file: Icon icon = new ImageIcon("photo.gif"); TestButtonIconsRun

13 Liang,Introduction to Java Programming,revised by Dai-kaiyu 13 Default Icons, Pressed Icon, and Rollover Icon A regular button has a default icon, pressed icon, and rollover icon. Normally, you use the default icon. All other icons are for special effects. A pressed icon is displayed when a button is pressed and a rollover icon is displayed when the mouse is over the button but pressed. (A) Default icon (B) Pressed icon (C) Rollover icon

14 Liang,Introduction to Java Programming,revised by Dai-kaiyu 14 Horizontal Alignments Horizontal alignment specifies how the icon and text are placed horizontally on a button. You can set the horizontal alignment using one of the five constants: LEADING, LEFT, CENTER, RIGHT, TRAILING. At present, LEADING and LEFT are the same and TRAILING and RIGHT are the same. Future implementation may distinguish them. The default horizontal alignment is SwingConstants.TRAILING. See figure 13.7 Vertical Alignments Vertical alignment specifies how the icon and text are placed vertically on a button. You can set the vertical alignment using one of the three constants: TOP, CENTER, BOTTOM. The default vertical alignment is SwingConstants.CENTER.

15 Liang,Introduction to Java Programming,revised by Dai-kaiyu 15 Horizontal Text Positions Horizontal text position specifies the horizontal position of the text relative to the icon. You can set the horizontal text position using one of the five constants: LEADING, LEFT, CENTER, RIGHT, TRAILING. The default horizontal text position is SwingConstants.RIGHT.

16 Liang,Introduction to Java Programming,revised by Dai-kaiyu 16 Vertical Text Positions Vertical text position specifies the vertical position of the text relative to the icon. You can set the vertical text position using one of the three constants: TOP, CENTER. The default vertical text position is SwingConstants.CENTER.

17 Liang,Introduction to Java Programming,revised by Dai-kaiyu 17 Example 13.1: Using Buttons Write a program that displays a message on a panel and uses two buttons,, to move the message on the panel to the left or right. Run ButtonDemo setMnemonic (using alt key) getSource() to judge the source UI

18 Liang,Introduction to Java Programming,revised by Dai-kaiyu 18 JCheckBox JCheckBox inherits all the properties such as text, icon, mnemonic, verticalAlignment, horizontalAlignment, horizontalTextPosition, verticalTextPosition, and selected from AbstractButton, and provides several constructors to create check boxes.

19 Liang,Introduction to Java Programming,revised by Dai-kaiyu 19 Example 13.2: Using Check Boxes Add three check boxes named Centered, Bold, and Italic into Example 13.1 to let the user specify whether the message is centered, bold, or italic. CheckBoxDemoRun ButtonDemo CheckBoxDemo

20 Liang,Introduction to Java Programming,revised by Dai-kaiyu 20 JRadioButton Radio buttons are variations of check boxes. They are often used in the group, where only one button is checked at a time.

21 Liang,Introduction to Java Programming,revised by Dai-kaiyu 21 Grouping Radio Buttons ButtonGroup btg = new ButtonGroup(); btg.add(jrb1); btg.add(jrb2);

22 Liang,Introduction to Java Programming,revised by Dai-kaiyu 22 Example 13.3: Using Radio Buttons Add three radio buttons named Red, Green, and Blue into the preceding example to let the user choose the color of the message. RunRadioButtonDemo ButtonDemo CheckBoxDemo RadioButtonDemo

23 Liang,Introduction to Java Programming,revised by Dai-kaiyu 23 JLabel A label is a display area for a short text, an image, or both.

24 Liang,Introduction to Java Programming,revised by Dai-kaiyu 24 JLabel Constructors The constructors for labels are as follows: JLabel() JLabel(String text, int horizontalAlignment) JLabel(String text) JLabel(Icon icon) JLabel(Icon icon, int horizontalAlignment) JLabel(String text, Icon icon, int horizontalAlignment)

25 Liang,Introduction to Java Programming,revised by Dai-kaiyu 25 JLabel Properties JLabel inherits all the properties from JComponent and has many properties similar to the ones in JButton, such as text, icon, horizontalAlignment, verticalAlignment, horizontalTextPosition, verticalTextPosition, and iconTextGap.

26 Liang,Introduction to Java Programming,revised by Dai-kaiyu 26 Using Labels // Create an image icon from image file ImageIcon icon = new ImageIcon("image/grapes.gif"); // Create a label with text, an icon, // with centered horizontal alignment JLabel jlbl = new JLabel("Grapes", icon, SwingConstants.CENTER); // Set label's text alignment and gap between text and icon jlbl.setHorizontalTextPosition(SwingConstants.CENTER); jlbl.setVerticalTextPosition(SwingConstants.BOTTOM); jlbl.setIconTextGap(5);

27 Liang,Introduction to Java Programming,revised by Dai-kaiyu 27 JTextField A text field is an input area where the user can type in characters. Text fields are useful in that they enable the user to enter in variable data (such as a name or a description).

28 Liang,Introduction to Java Programming,revised by Dai-kaiyu 28 JTextField Constructors JTextField(int columns) Creates an empty text field with the specified number of columns. JTextField(String text) Creates a text field initialized with the specified text. JTextField(String text, int columns) Creates a text field initialized with the specified text and the column size.

29 Liang,Introduction to Java Programming,revised by Dai-kaiyu 29 JTextField Properties text horizontalAlignment editable columns

30 Liang,Introduction to Java Programming,revised by Dai-kaiyu 30 JTextField Methods getText() Returns the string from the text field. setText(String text) Puts the given string in the text field. setEditable(boolean editable) Enables or disables the text field to be edited. By default, editable is true. setColumns(int) Sets the number of columns in this text field. The length of the text field is changeable.

31 Liang,Introduction to Java Programming,revised by Dai-kaiyu 31 Example 13.4: Using Text Fields Add a text field to the preceding example to let the user set a new message. Run TextFieldDemo frame.pack() automatically sizes up the frame according to the size of the components places in it

32 Liang,Introduction to Java Programming,revised by Dai-kaiyu 32 JTextArea JTextArea enables the user to enter multiple lines of text.

33 Liang,Introduction to Java Programming,revised by Dai-kaiyu 33 JTextArea Constructors JTextArea(int rows, int columns) Creates a text area with the specified number of rows and columns. JTextArea(String s, int rows, int columns) Creates a text area with the initial text and the number of rows and columns specified.

34 Liang,Introduction to Java Programming,revised by Dai-kaiyu 34 JTextArea Properties text editable columns lineWrap wrapStyleWord rows lineCount tabSize

35 Liang,Introduction to Java Programming,revised by Dai-kaiyu 35 Example 13.5 Using Text Areas This example gives a program that displays an image in a label, a title in a label, and a text in a text area.

36 Liang,Introduction to Java Programming,revised by Dai-kaiyu 36 Example 13.5, cont. Run TextAreaDemo

37 Liang,Introduction to Java Programming,revised by Dai-kaiyu 37 JComboBox A combo box is a simple list of items from which the user can choose. It performs basically the same function as a list, but can get only one value.

38 Liang,Introduction to Java Programming,revised by Dai-kaiyu 38 JComboBox Methods To add an item to a JComboBox jcbo, use jcbo.addItem(Object item) To get an item from JComboBox jcbo, use jcbo.getItem()

39 Liang,Introduction to Java Programming,revised by Dai-kaiyu 39 Using the itemStateChanged Handler public void itemStateChanged(ItemEvent e) { // Make sure the source is a combo box if (e.getSource() instanceof JComboBox) String s = (String)e.getItem(); } When a choice is checked or unchecked, itemStateChanged() for ItemEvent is invoked as well as the actionPerformed() handler for ActionEvent.

40 Liang,Introduction to Java Programming,revised by Dai-kaiyu 40 Example 13.6: Using Combo Boxes This example lets users view an image and a description of a country's flag by selecting the country from a combo box. RunComboBoxDemo

41 Liang,Introduction to Java Programming,revised by Dai-kaiyu 41 JList A list is a component that performs basically the same function as a combo box, but it enables the user to choose a single value or multiple values.

42 Liang,Introduction to Java Programming,revised by Dai-kaiyu 42 JList Constructors JList() Creates an empty list. JList(Object[] stringItems) Creates a new list initialized with items.

43 Liang,Introduction to Java Programming,revised by Dai-kaiyu 43 JList Properties selectedIndexd selectedIndices selectedValue selectedValues selectionMode visibleRowCount

44 Liang,Introduction to Java Programming,revised by Dai-kaiyu 44 Example 13.7: Using Lists This example gives a program that lets users select countries in a list and display the flags of the selected countries in the labels. RunListDemo Jlabel.setIcon(null);

45 Liang,Introduction to Java Programming,revised by Dai-kaiyu 45 JScrollBar A scroll bar is a control that enables the user to select from a range of values. The scrollbar appears in two styles: horizontal and vertical.

46 Liang,Introduction to Java Programming,revised by Dai-kaiyu 46 Scroll Bar Properties

47 Liang,Introduction to Java Programming,revised by Dai-kaiyu 47 Scroll Bar event-driven model JScrollBar Change the value of Generate AdjustmentEvent AdjustmentListener register adjustmentValueChanged

48 Liang,Introduction to Java Programming,revised by Dai-kaiyu 48 Example 13.8: Using Scrollbars This example uses horizontal and vertical scrollbars to control a message displayed on a panel. The horizontal scrollbar is used to move the message to the left or the right, and the vertical scrollbar to move it up and down. ScrollBarDemoRun

49 Liang,Introduction to Java Programming,revised by Dai-kaiyu 49 JSlider JSlider is similar to JScrollBar, but JSlider has more properties and can appear in many forms.

50 Liang,Introduction to Java Programming,revised by Dai-kaiyu 50 Scroll Bar event-driven model JSlider Change the value of Generate ChangedEvent ChangeListener register stateChanged

51 Liang,Introduction to Java Programming,revised by Dai-kaiyu 51 Example 13.9: Using Sliders Rewrite the preceding program using the sliders to control a message displayed on a panel instead of using scroll bars. SliderDemoRun jsldHort.setPaintLabels(true); jsldHort.setPaintTicks(true); jsldHort.setMajorTickSpacing(10); jsldHort.setMinorTickSpacing(1); jsldHort.setPaintTrack(false); jsldVert.setInverted(true);

52 Liang,Introduction to Java Programming,revised by Dai-kaiyu 52

53 Liang,Introduction to Java Programming,revised by Dai-kaiyu 53 Creating Multiple Windows The following slides show step-by-step how to create an additional window from an application or applet.

54 Liang,Introduction to Java Programming,revised by Dai-kaiyu 54 Step 1: Create a subclass of JFrame (called a SubFrame ) that tells the new window what to do. For example, all the GUI application programs extend JFrame and are subclasses of JFrame. Creating Additional Windows, Step 1

55 Liang,Introduction to Java Programming,revised by Dai-kaiyu 55 Creating Additional Windows, Step 2 Step 2: Create an instance of SubFrame in the application or applet. Example: SubFrame subFrame = new SubFrame("SubFrame Title");

56 Liang,Introduction to Java Programming,revised by Dai-kaiyu 56 Creating Additional Windows, Step 3 Step 3: Create a JButton for activating the subFrame. add(new JButton("Activate SubFrame"));

57 Liang,Introduction to Java Programming,revised by Dai-kaiyu 57 Creating Additional Windows, Step 4 Step 4: Override the actionPerformed() method as follows: public actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); if (e.target instanceof Button) { if ("Activate SubFrame".equals(actionCommand)) { subFrame.setVisible(true); }

58 Liang,Introduction to Java Programming,revised by Dai-kaiyu 58 Example 13.10 Creating Multiple Windows This example creates a main window with a text area in the scroll pane, and a button named "Show Histogram." When the user clicks the button, a new window appears that displays a histogram to show the occurrence of the letters in the text area.

59 Liang,Introduction to Java Programming,revised by Dai-kaiyu 59 Example 13.10, cont. RunMultipleWindowsDemo Histogram

60 Liang,Introduction to Java Programming,revised by Dai-kaiyu 60 Using Menus with Frames Menus  Allows for performing actions with cluttering GUI  Contained by menu bar JMenuBar  Comprised of menu items JMenuItem

61 Liang,Introduction to Java Programming,revised by Dai-kaiyu61 1 // Fig. 13.10: MenuTest.java 2 // Demonstrating menus 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class MenuTest extends JFrame { 12 private Color colorValues[] = 13 { Color.black, Color.blue, Color.red, Color.green }; 14 15 private JRadioButtonMenuItem colorItems[], fonts[]; 16 private JCheckBoxMenuItem styleItems[]; 17 private JLabel displayLabel; 18 private ButtonGroup fontGroup, colorGroup; 19 private int style; 20 21 // set up GUI 22 public MenuTest() 23 { 24 super( "Using JMenus" ); 25 26 // set up File menu and its menu items 27 JMenu fileMenu = new JMenu( "File" ); 28 fileMenu.setMnemonic( 'F' ); 29 30 // set up About... menu item 31 JMenuItem aboutItem = new JMenuItem( "About..." ); 32 aboutItem.setMnemonic( 'A' ); 33 34 aboutItem.addActionListener( 35 Instantiate File JMenu Instantiate About… JMenuItem to be placed in fileMenu

62 Liang,Introduction to Java Programming,revised by Dai-kaiyu62 36 // anonymous inner class to handle menu item event 37 new ActionListener() { 38 39 // display message dialog when user selects About... 40 public void actionPerformed( ActionEvent event ) 41 { 42 JOptionPane.showMessageDialog( MenuTest.this, 43 "This is an example\nof using menus", 44 "About", JOptionPane.PLAIN_MESSAGE ); 45 } 46 47 } // end anonymous inner class 48 49 ); // end call to addActionListener 50 51 fileMenu.add( aboutItem ); 52 53 // set up Exit menu item 54 JMenuItem exitItem = new JMenuItem( "Exit" ); 55 exitItem.setMnemonic( 'x' ); 56 57 exitItem.addActionListener( 58 59 // anonymous inner class to handle exitItem event 60 new ActionListener() { 61 62 // terminate application when user clicks exitItem 63 public void actionPerformed( ActionEvent event ) 64 { 65 System.exit( 0 ); 66 } 67 68 } // end anonymous inner class 69 70 ); // end call to addActionListener When user selects About… JMenuItem, display message dialog with appropriate text Instantiate Exit JMenuItem to be placed in fileMenu When user selects Exit JMenuItem, exit system Refer to MenuTest Modal Dialog

63 Liang,Introduction to Java Programming,revised by Dai-kaiyu63 71 72 fileMenu.add( exitItem ); 73 74 // create menu bar and attach it to MenuTest window 75 JMenuBar bar = new JMenuBar(); 76 setJMenuBar( bar ); 77 bar.add( fileMenu ); 78 79 // create Format menu, its submenus and menu items 80 JMenu formatMenu = new JMenu( "Format" ); 81 formatMenu.setMnemonic( 'r' ); 82 83 // create Color submenu 84 String colors[] = { "Black", "Blue", "Red", "Green" }; 85 86 JMenu colorMenu = new JMenu( "Color" ); 87 colorMenu.setMnemonic( 'C' ); 88 89 colorItems = new JRadioButtonMenuItem[ colors.length ]; 90 colorGroup = new ButtonGroup(); 91 ItemHandler itemHandler = new ItemHandler(); 92 93 // create color radio button menu items 94 for ( int count = 0; count < colors.length; count++ ) { 95 colorItems[ count ] = 96 new JRadioButtonMenuItem( colors[ count ] ); 97 98 colorMenu.add( colorItems[ count ] ); 99 colorGroup.add( colorItems[ count ] ); 100 101 colorItems[ count ].addActionListener( itemHandler ); 102 } 103 104 // select first Color menu item 105 colorItems[ 0 ].setSelected( true ); Instantiate JMenuBar to contain JMenu s Instantiate Format JMenu Instantiate Color JMenu (submenu of Format JMenu ) Instantiate JRadioButtonMenuItem s for Color JMenu and ensure that only one menu item is selected at a time

64 Liang,Introduction to Java Programming,revised by Dai-kaiyu64 106 107 // add format menu to menu bar 108 formatMenu.add( colorMenu ); 109 formatMenu.addSeparator(); 110 111 // create Font submenu 112 String fontNames[] = { "Serif", "Monospaced", "SansSerif" }; 113 114 JMenu fontMenu = new JMenu( "Font" ); 115 fontMenu.setMnemonic( 'n' ); 116 117 fonts = new JRadioButtonMenuItem[ fontNames.length ]; 118 fontGroup = new ButtonGroup(); 119 120 // create Font radio button menu items 121 for ( int count = 0; count < fonts.length; count++ ) { 122 fonts[ count ] = 123 new JRadioButtonMenuItem( fontNames[ count ] ); 124 125 fontMenu.add( fonts[ count ] ); 126 fontGroup.add( fonts[ count ] ); 127 128 fonts[ count ].addActionListener( itemHandler ); 129 } 130 131 // select first Font menu item 132 fonts[ 0 ].setSelected( true ); 133 134 fontMenu.addSeparator(); 135 136 // set up style menu items 137 String styleNames[] = { "Bold", "Italic" }; 138 139 styleItems = new JCheckBoxMenuItem[ styleNames.length ]; 140 StyleHandler styleHandler = new StyleHandler(); Separator places line between JMenuItem s Instantiate Font JMenu (submenu of Format JMenu ) Instantiate JRadioButtonMenuItem s for Font JMenu and ensure that only one menu item is selected at a time

65 Liang,Introduction to Java Programming,revised by Dai-kaiyu65 141 142 // create style checkbox menu items 143 for ( int count = 0; count < styleNames.length; count++ ) { 144 styleItems[ count ] = 145 new JCheckBoxMenuItem( styleNames[ count ] ); 146 147 fontMenu.add( styleItems[ count ] ); 148 149 styleItems[ count ].addItemListener( styleHandler ); 150 } 151 152 // put Font menu in Format menu 153 formatMenu.add( fontMenu ); 154 155 // add Format menu to menu bar 156 bar.add( formatMenu ); 157 158 // set up label to display text 159 displayLabel = new JLabel( 160 "Sample Text", SwingConstants.CENTER ); 161 displayLabel.setForeground( colorValues[ 0 ] ); 162 displayLabel.setFont( 163 new Font( "TimesRoman", Font.PLAIN, 72 ) ); 164 165 getContentPane().setBackground( Color.cyan ); 166 getContentPane().add( displayLabel, BorderLayout.CENTER ); 167 168 setSize( 500, 200 ); 169 setVisible( true ); 170 171 } // end constructor 172

66 Liang,Introduction to Java Programming,revised by Dai-kaiyu66 173 // execute application 174 public static void main( String args[] ) 175 { 176 MenuTest application = new MenuTest(); 177 178 application.setDefaultCloseOperation( 179 JFrame.EXIT_ON_CLOSE ); 180 } 181 182 // inner class to handle action events from menu items 183 private class ItemHandler implements ActionListener { 184 185 // process color and font selections 186 public void actionPerformed( ActionEvent event ) 187 { 188 // process color selection 189 for ( int count = 0; count < colorItems.length; count++ ) 190 191 if ( colorItems[ count ].isSelected() ) { 192 displayLabel.setForeground( colorValues[ count ] ); 193 break; 194 } 195 196 // process font selection 197 for ( int count = 0; count < fonts.length; count++ ) 198 199 if ( event.getSource() == fonts[ count ] ) { 200 displayLabel.setFont( new Font( 201 fonts[ count ].getText(), style, 72 ) ); 202 break; 203 } 204 205 repaint(); 206 } 207 Invoked when user selects JMenuItem Determine which font or color menu generated event Set font or color of JLabel, respectively

67 Liang,Introduction to Java Programming,revised by Dai-kaiyu67 208 } // end class ItemHandler 209 210 // inner class to handle item events from check box menu items 211 private class StyleHandler implements ItemListener { 212 213 // process font style selections 214 public void itemStateChanged( ItemEvent e ) 215 { 216 style = 0; 217 218 // check for bold selection 219 if ( styleItems[ 0 ].isSelected() ) 220 style += Font.BOLD; 221 222 // check for italic selection 223 if ( styleItems[ 1 ].isSelected() ) 224 style += Font.ITALIC; 225 226 displayLabel.setFont( new Font( 227 displayLabel.getFont().getName(), style, 72 ) ); 228 229 repaint(); 230 } 231 232 } // end class StyleHandler 233 234 } // end class MenuTest Invoked when user selects JCheckBoxMenuItem Determine new font style

68 Liang,Introduction to Java Programming,revised by Dai-kaiyu68 MenuTest.java Program Output


Download ppt "Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 13 Creating User Interfaces …Starry starry night flaming flowers that brightly blaze."

Similar presentations


Ads by Google