Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Chapter 13 Creating User Interfaces Chapter 8 Inheritance and Polymorphism Chapter 9 Abstract Classes and Interfaces Chapter 11 Getting Started with GUI Programming Chapter 12 Event-Driven Programming Chapter 13 Creating User Interfaces Chapter 14 Applets, Images, Audio Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 1 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). Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 2 Components Covered in the Chapter Introduces the frequently used GUI components Uses borders and icons JButton Component Container JComponent AbstractButton JCheckBox JToggleButton JRadioButton JLabel JTextField JTextComponent JTextArea JComboBox JList JScrollBar JSlider Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 3 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, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 4 Test Swing Common Features Component Properties JComponent Properties font background foreground preferredSize minimumSize maximumSize toolTipText border TestSwingCommonFeatures Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 5 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, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 6 JButton JButton inherits AbstractButton and provides several constructors to create buttons. javax.swing.AbstractButton javax.swing.JButton +JButton() Creates a default button with no text and icon. +JButton(icon: javax.swing.Icon) Creates a button with an icon. +JButton(text: String) Creates a button with text. +JButton(text: String, icon: Icon) Creates a button with text and an icon. Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 7 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"); TestButtonIcons Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 8 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, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 9 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. Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 10 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, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 11 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, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 12 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, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 13 Example 13.1: Using Buttons Write a program that displays a message on a panel and uses two buttons, <= and =>, to move the message on the panel to the left or right. ButtonDemo MessagePanel JButton JButton Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 14 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. javax.swing.AbstractButton javax.swing.JToggleButton javax.swing.JCheckBox +JCheckBox() Creates a default check box button with no text and icon. +JCheckBox(text: String) Creates a check box with text. +JCheckBox(text: String, selected: boolean) Creates a check box with text and specifies whether the check box is initially selected. +JCheckBox(icon: Icon) Creates a checkbox with an icon. +JCheckBox(text: String, icon: Icon) Creates a checkbox with text and an icon. +JCheckBox(text: String, icon: Icon, selected: boolean) Creates a check box with text and an icon, and specifies whether the check box is initially selected. Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 15 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. ButtonDemo CheckBoxDemo CheckBoxDemo Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 16 JRadioButton Radio buttons are variations of check boxes. They are often used in the group, where only one button is checked at a time. javax.swing.AbstractButton javax.swing.JToggleButton javax.swing.JRadioButton +JRadioButton() Creates a default radio button with no text and icon. +JRadioButton(text: String) Creates a radio button with text. +JRadioButton(text: String, selected: boolean) Creates a radio button with text and specifies whether the radio button is initially selected. +JRadioButton(icon: Icon) Creates a radio button with an icon. +JRadioButton(text: String, icon: Icon) Creates a radio button with text and an icon. +JRadioButton(text: String, icon: Icon, selected: boolean) Creates a radio button with text and an icon, and specifies whether the radio button is initially selected. Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 17 Grouping Radio Buttons ButtonGroup btg = new ButtonGroup(); btg.add(jrb1); btg.add(jrb2); Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 18 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. ButtonDemo CheckBoxDemo RadioButtonDemo RadioButtonDemo Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 19 JLabel A label is a display area for a short text, an image, or both. javax.swing.JComponent javax.swing.JLabel +JLabel() Creates a default label with no text and icon. +JLabel(icon: javax.swing.Icon) Creates a label with an icon. +JLabel(icon: Icon, hAlignment: int) Creates a label with an icon and the specified horizontal alignment. +JLabel(text: String) Creates a label with text. +JLabel(text: String, icon: Icon, hAlignment: int) Creates a label with text, an icon and the specified horizontal alignment. +JLabel(text: String, hAlignment: int) Creates a label with text and the specified horizontal alignment. +getText(): String Returns the label’s text. +setText(text: String): void Sets the label’s text. +getIcon(): javax.swing.Icon Returns the label’s image icon. +setIcon(icon: Icon): void Sets an image icon on the label. +getHorizontalAlignment(): int Returns the horizontal alignment of the text and icon on the label. +setHorizontalAlignment(alignment: int): Sets the horizontal alignment – same as for buttons. void +getHorizontalTextPosition(): int Returns the horizontal text position relative to the icon on the label. +setHorizontalTextPosition(textPosition: Sets the horizontal text position – same as for buttons. int): void +getVerticalAlignment(): int Returns the vertical alignment of the text and icon on the label. +setVerticalAlignment(vAlignment: int): Sets the vertical alignment – same as for buttons. void +getVerticalTextPosition(): int Returns the vertical text position relative to the icon on the label. +setVerticalTextPosition(vTextPosition: int) : void Sets the vertical text position – same as for buttons +getIconTextGap(): int Returns the gap between the text and the icon on the label. (JDK 1.4) +setIconTextGap(iconTextGap: int): void Sets a gap between the text and the icon on the label. (JDK 1.4) Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 20 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, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 21 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). javax.swing.text.JTextComponent +getText(): String Returns the text contained in this text component. +setText(text: String): void Sets a text in this text component. +isEditable(): boolean Indicates whether this text component is editable. +setEditable(b: boolean): void Sets the text component editable or prevents it from being edited. (default: true) javax.swing.JTextField +JTextField() Creates a default empty text field with number of columns set to 0. +JTextField(column: int) Creates an empty text field with specified number of columns. +JTextField(text: String) Creates a text field initialized with the specified text. +JTextField(text: String, columns: int) Creates a text field initialized with the specified text and columns. +getColumns(): int Returns the number of columns in this text field. +setColumns(columns: int): void Sets the number of columns in this text field. +getHorizontalAlignment(): int Returns the horizontal alignment of this text field. Liang, Introduction to Java Fifth Edition, (c) 2005 Pearson All +setHorizontalAlignment(alignment: int): voidProgramming, Sets the horizontal alignment for thisEducation, text field.Inc. (default: LEFT) rights reserved. 0-13-148952-6 22 Example 13.4: Using Text Fields Add a text field to the preceding example to let the user set a new message. ActionListener ButtonDemo CheckBoxDemo RadioButtonDemo TextFieldDemo JFrame TextFieldDemo Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 23 JTextArea If you want to let the user enter multiple lines of text, you cannot use text fields unless you create several of them. The solution is to use JTextArea, which enables the user to enter multiple lines of text. javax.swing.text.JTextComponent javax.swing.JTextArea +JTextArea() Creates a default empty text area. +JTextArea(rows: int, columns: int) Creates an empty text area with the specified number of rows and columns. +JTextArea(text: String) Creates a new text area with the specified text displayed. +JTextArea(text: String, rows: int, columns: int) Creates a new text area with the specified text and number of rows and columns. +append(s: String): void Appends the string to text in the text area. +insert(s: String, pos: int): void Inserts string s in the specified position in the text area. +replaceRange(s: String, start: int, end: int): void Replaces partial text in the range from position start to end with string s. +getColumns(): int Returns the number of columns in this text area. +setColumns(columns: int): void Sets the number of columns in this text area. +getRows(): int Returns the number of rows in this text area. +setRows(rows: int): void Sets the number of rows in this text area. +getLineCount(): int Returns the actual number of lines contained in the text area. +getTabSize(): int Returns the number of characters used to expand tabs in this text area. +setTabSize(size: int): void Sets the number of characters to expand tabs to. (default: 8) +getLineWrap(): boolean Indicates whether the line in the text area is automatically wrapped. +setLineWrap(wrap: boolean): void Sets the line-wrapping policy of the text area. (default: false) +getWrapStyleWord(): boolean Indicates whether the line is wrapped on words or characters. +setWrapStyleWord(word: boolean): void Sets the style of wrapping used if the text area is wrapping lines. The default Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All value is false, which indicates that the line is wrapped on characters. 24 rights reserved. 0-13-148952-6 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. JPanel JFrame -char token +getToken DescriptionPanel +setToken +paintComponet -jlblImage: JLabel +mouseClicked -jlblTitle: JLabel -jtaTextDescription: JTextArea -char token 1 1 +getToken TextAreaDemo +setToken +paintComponet +mouseClicked +setImageIcon(icon: ImageIcon): void +setTitle(title: String): void +setTextDescription(text: String): void +getMinimumSize(): Dimension Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 25 Example 13.5, cont. TextAreaDemo Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 26 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. javax.swing.JComponent javax.swing.JComboBox +JComboBox() Creates a default empty combo box. +JComboBox(items: Object[]) Creates a combo box that contains the elements in the specified array. +addItem(item: Object): void Adds an item to the combo box. +getItemAt(index: int): Object Returns the item at the specified index. +getItemCount(): int Returns the number of items in the combo box. +getSelectedIndex(): int Returns the index of the selected item. +setSelectedIndex(index: int): void Sets the selected index in the combo box. +getSelectedItem(): Object Returns the selected item. +setSelectedItem(item: Object): void Sets the selected item in the combo box. +removeItem(anObject: Object): void Removes an item from the item list. Removes the item at the specified index in the combo box. +removeItemAt(anIndex: int): void +removeAllItems(): void Removes all items in the combo box. Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 27 Using the itemStateChanged Handler When a choice is checked or unchecked, itemStateChanged() for ItemEvent is invoked as well as the actionPerformed() handler for ActionEvent. public void itemStateChanged(ItemEvent e) { // Make sure the source is a combo box if (e.getSource() instanceof JComboBox) String s = (String)e.getItem(); } Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 28 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. ComboBoxDemo Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 29 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. javax.swing.JComponent javax.swing.JList +JList() Creates a default empty list. +JList(items: Object[]) Creates a list that contains the elements in the specified array. +getSelectedIndex(): int Returns the index of the first selected item. +setSelectedIndex(index: int): void Selects the cell at the specified index. +getSelectedIndices(): int[] Returns an array of all of the selected indices in increasing order. +setSelectedIndices(indices: int[]): void Selects the cells at the specified indices. +getSelectedValue(): Object Returns the first selected item in the list. +getSelectedValues(): Object[] Returns an array of the values for the selected cells in increasing index order. +getVisibleRowCount(): int Returns the number of visible rows displayed without a scrollbar. (default: 8) +setVisibleRowCount(count: int): void Sets the preferred number of visible rows displayed without a scrollbar. +getSelectionBackground(): Color Returns the background color of the selected cells. +setSelectionBackground(c: Color): void Sets the background color of the selected cells. +getSelectionForeground(): Color Returns the foreground color of the selected cells. +setSelectionForeground(c: Color): void Sets the foreground color of the selected cells. +getSelectionMode(): int Returns the selection mode for the list. Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All +setSelectionMode(selectionMode: int): Sets thereserved. selection mode for the list. rights 0-13-148952-6 30 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. ListDemo Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 31 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. javax.swing.JComponent javax.swing.JScrollBar +JScrollBar() Creates a default vertical scroll bar. +JScrollBar(orientation: int) Creates a scroll bar with the specified orientation. +JScrollBar(orientation: int, value: int, extent: int, min: int, max: int) Creates a scrollbar with the specified orientation, value, extent, minimum, and maximum. +getBlockIncrement(): int Returns the block increment. +setBlockIncrement(increment: int): void Sets a new block increment. (default: 10) +getMaximum(): int Returns the maximum value represented by the scroll bar. +setMaximum(maximum: int): void Sets a new maximum. (default: 100) +getMinimum(): int Returns the minimum value represented by the scroll bar. +setMinimum(minimum: int): void Sets a new minimum. (default: 0) +getOrientation(): int Returns the orientation of the scroll bar. +setOrientation(orientation: int): void Sets a new orientation for the scroll bar. +getUnitIncrement(): int Returns the unit increment in the scroll bar. +setUnitIncrement(increment: int): void Sets a new unit increment in the scroll bar. +getValue(): int Returns the current value represented by the scroll bar. +setValue(int value): void Sets a new current value represented by the scroll bar. +getVisibleAmount(): int Returns the visible amount in the scroll bar. Liang, Introduction to Java Programming, Fifth (c) 2005 Pearson Education, Inc. All +setVisibleAmount(extent: int): void Sets Edition, a new visible amount for the scroll bar. (default: 10) rights reserved. 0-13-148952-6 32 Scroll Bar Properties Minimal value Maximal value Block decrement Block increment Bubble Unit decrement Unit increment Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 33 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. ScrollBarDemo Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 34 JSlider JSlider is similar to JScrollBar, but JSlider has more properties and can appear in many forms. javax.swing.JComponent javax.swing.JSlider +JSlider() Creates a default horizontal slider. +JSlider(min: int, max: int) Creates a horizontal slider using the specified min and max. +JSlider(min: int, max: int, value: int) Creates a horizontal slider using the specified min, max, and value. +JSlider(orientation: int) Creates a slider with the specified orientation. +JSlider(orientation: int, min: int, max: int, value: int) Creates a slider with the specified orientation, min, max, and value. +getInverted(): boolean Returns true if the value-range shown for the slider is reversed. +setInverted(b: boolean): void Sets true to reverse the value-range, and false to put the value range in the normal order. (default: false) +getMajorTickSpacing(): int Returns the number of units between major ticks. +setMajorTickSpacing(n: int): void Sets the number of units between major ticks. (default: 0) +getMinorTickSpacing(): int Returns the number of units between minor ticks. +setMinorTickSpacing(n: int): void Sets the number of units between minor ticks. (default: 0) +getMaximum(): int Returns the maximum value represented by the slider. +setMaximum(maximum: int): void Sets a new maximum. (default: 100) +getMinimum(): int Returns the minimum value represented by the slider. +setMinimum(minimum: int): void Sets a new minimum. (default: 0) +getOrientation(): int Returns the orientation of the slider. +setOrientation(orientation: int): void Sets a new orientation for the slider. +getPaintLabels(): boolean Returns true if the labels are painted at tick marks. +setPaintLabels(b: boolean): void Sets a Boolean value to determine whether labels are painted. (default: false) +getPaintTicks(): boolean Returns true if the ticks are painted on the slider. +setPaintTicks(b: boolean): void Sets a Boolean value to determine whether ticks are painted. (default: false) +getPaintTrack(): boolean Returns true if the track are painted on the slider. +setPaintTrack(b: boolean): void Sets a Boolean value to determine whether tracks are painted. (default: true) +getValue(): int Returns the current value represented by the slider. +setValue(int value): void a new value represented by the Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Sets Pearson Education, Inc. Allslider. rights reserved. 0-13-148952-6 35 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. SliderDemo Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 36 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, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 37 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. Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 38 Example 13.10, cont. MultipleWindowsDemo Histogram Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved. 0-13-148952-6 39