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….
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
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu 4
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”));
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
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu 8
9 JButton JButton inherits AbstractButton and provides several constructors to create buttons.
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)
Liang,Introduction to Java Programming,revised by Dai-kaiyu 11 JButton Properties text icon mnemonic horizontalAlignment verticalAlignment horizontalTextPosition verticalTextPosition iconTextGap
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
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
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.
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.
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.
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
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.
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
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu 21 Grouping Radio Buttons ButtonGroup btg = new ButtonGroup(); btg.add(jrb1); btg.add(jrb2);
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
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.
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)
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.
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);
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).
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu 29 JTextField Properties text horizontalAlignment editable columns
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.
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu 32 JTextArea JTextArea enables the user to enter multiple lines of text.
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu 34 JTextArea Properties text editable columns lineWrap wrapStyleWord rows lineCount tabSize
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu 36 Example 13.5, cont. Run TextAreaDemo
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.
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()
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.
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
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.
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu 43 JList Properties selectedIndexd selectedIndices selectedValue selectedValues selectionMode visibleRowCount
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);
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu 46 Scroll Bar Properties
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
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
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.
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
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);
Liang,Introduction to Java Programming,revised by Dai-kaiyu 52
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.
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
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");
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"));
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); }
Liang,Introduction to Java Programming,revised by Dai-kaiyu 58 Example 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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu 59 Example 13.10, cont. RunMultipleWindowsDemo Histogram
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu61 1 // Fig : 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.*; public class MenuTest extends JFrame { 12 private Color colorValues[] = 13 { Color.black, Color.blue, Color.red, Color.green }; private JRadioButtonMenuItem colorItems[], fonts[]; 16 private JCheckBoxMenuItem styleItems[]; 17 private JLabel displayLabel; 18 private ButtonGroup fontGroup, colorGroup; 19 private int style; // set up GUI 22 public MenuTest() 23 { 24 super( "Using JMenus" ); // set up File menu and its menu items 27 JMenu fileMenu = new JMenu( "File" ); 28 fileMenu.setMnemonic( 'F' ); // set up About... menu item 31 JMenuItem aboutItem = new JMenuItem( "About..." ); 32 aboutItem.setMnemonic( 'A' ); aboutItem.addActionListener( 35 Instantiate File JMenu Instantiate About… JMenuItem to be placed in fileMenu
Liang,Introduction to Java Programming,revised by Dai-kaiyu62 36 // anonymous inner class to handle menu item event 37 new ActionListener() { // display message dialog when user selects About 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 } } // end anonymous inner class ); // end call to addActionListener fileMenu.add( aboutItem ); // set up Exit menu item 54 JMenuItem exitItem = new JMenuItem( "Exit" ); 55 exitItem.setMnemonic( 'x' ); exitItem.addActionListener( // anonymous inner class to handle exitItem event 60 new ActionListener() { // terminate application when user clicks exitItem 63 public void actionPerformed( ActionEvent event ) 64 { 65 System.exit( 0 ); 66 } } // end anonymous inner class ); // 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
Liang,Introduction to Java Programming,revised by Dai-kaiyu fileMenu.add( exitItem ); // create menu bar and attach it to MenuTest window 75 JMenuBar bar = new JMenuBar(); 76 setJMenuBar( bar ); 77 bar.add( fileMenu ); // create Format menu, its submenus and menu items 80 JMenu formatMenu = new JMenu( "Format" ); 81 formatMenu.setMnemonic( 'r' ); // create Color submenu 84 String colors[] = { "Black", "Blue", "Red", "Green" }; JMenu colorMenu = new JMenu( "Color" ); 87 colorMenu.setMnemonic( 'C' ); colorItems = new JRadioButtonMenuItem[ colors.length ]; 90 colorGroup = new ButtonGroup(); 91 ItemHandler itemHandler = new ItemHandler(); // create color radio button menu items 94 for ( int count = 0; count < colors.length; count++ ) { 95 colorItems[ count ] = 96 new JRadioButtonMenuItem( colors[ count ] ); colorMenu.add( colorItems[ count ] ); 99 colorGroup.add( colorItems[ count ] ); colorItems[ count ].addActionListener( itemHandler ); 102 } // 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
Liang,Introduction to Java Programming,revised by Dai-kaiyu // add format menu to menu bar 108 formatMenu.add( colorMenu ); 109 formatMenu.addSeparator(); // create Font submenu 112 String fontNames[] = { "Serif", "Monospaced", "SansSerif" }; JMenu fontMenu = new JMenu( "Font" ); 115 fontMenu.setMnemonic( 'n' ); fonts = new JRadioButtonMenuItem[ fontNames.length ]; 118 fontGroup = new ButtonGroup(); // create Font radio button menu items 121 for ( int count = 0; count < fonts.length; count++ ) { 122 fonts[ count ] = 123 new JRadioButtonMenuItem( fontNames[ count ] ); fontMenu.add( fonts[ count ] ); 126 fontGroup.add( fonts[ count ] ); fonts[ count ].addActionListener( itemHandler ); 129 } // select first Font menu item 132 fonts[ 0 ].setSelected( true ); fontMenu.addSeparator(); // set up style menu items 137 String styleNames[] = { "Bold", "Italic" }; 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
Liang,Introduction to Java Programming,revised by Dai-kaiyu // create style checkbox menu items 143 for ( int count = 0; count < styleNames.length; count++ ) { 144 styleItems[ count ] = 145 new JCheckBoxMenuItem( styleNames[ count ] ); fontMenu.add( styleItems[ count ] ); styleItems[ count ].addItemListener( styleHandler ); 150 } // put Font menu in Format menu 153 formatMenu.add( fontMenu ); // add Format menu to menu bar 156 bar.add( formatMenu ); // 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 ) ); getContentPane().setBackground( Color.cyan ); 166 getContentPane().add( displayLabel, BorderLayout.CENTER ); setSize( 500, 200 ); 169 setVisible( true ); } // end constructor 172
Liang,Introduction to Java Programming,revised by Dai-kaiyu // execute application 174 public static void main( String args[] ) 175 { 176 MenuTest application = new MenuTest(); application.setDefaultCloseOperation( 179 JFrame.EXIT_ON_CLOSE ); 180 } // inner class to handle action events from menu items 183 private class ItemHandler implements ActionListener { // 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++ ) if ( colorItems[ count ].isSelected() ) { 192 displayLabel.setForeground( colorValues[ count ] ); 193 break; 194 } // process font selection 197 for ( int count = 0; count < fonts.length; count++ ) if ( event.getSource() == fonts[ count ] ) { 200 displayLabel.setFont( new Font( 201 fonts[ count ].getText(), style, 72 ) ); 202 break; 203 } repaint(); 206 } 207 Invoked when user selects JMenuItem Determine which font or color menu generated event Set font or color of JLabel, respectively
Liang,Introduction to Java Programming,revised by Dai-kaiyu } // end class ItemHandler // inner class to handle item events from check box menu items 211 private class StyleHandler implements ItemListener { // process font style selections 214 public void itemStateChanged( ItemEvent e ) 215 { 216 style = 0; // check for bold selection 219 if ( styleItems[ 0 ].isSelected() ) 220 style += Font.BOLD; // check for italic selection 223 if ( styleItems[ 1 ].isSelected() ) 224 style += Font.ITALIC; displayLabel.setFont( new Font( 227 displayLabel.getFont().getName(), style, 72 ) ); repaint(); 230 } } // end class StyleHandler } // end class MenuTest Invoked when user selects JCheckBoxMenuItem Determine new font style
Liang,Introduction to Java Programming,revised by Dai-kaiyu68 MenuTest.java Program Output