1 chapter 13 creating user interfaces. 2 objectives f to create graphical user interfaces with...

57
1 Chapter 13 Creating User Interfaces Prerequisites for Part III Chapter11 G etting Started w ith G U IProgram ming Chapter8 Inheritance and Polym orphism Chapter13 Creating U serInterfaces Chapter14 A pplets, Im ages,A udio Chapter9 A bstractClassesand Interfaces Chapter12 Event-D riven Program ming

Post on 19-Dec-2015

227 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

1

Chapter 13Creating User Interfaces

Prerequisites for Part III

Chapter 11 Getting Started with GUI Programming

Chapter 8 Inheritance and Polymorphism

Chapter 13 Creating User Interfaces

Chapter 14 Applets, Images, Audio

Chapter 9 Abstract Classes and Interfaces

Chapter 12 Event-Driven Programming

Page 2: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

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).

Page 3: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

3

Components Covered in the ChapterIntroduces the frequently used GUI componentsUses borders and icons

AbstractButton

JToggleButton

JCheckBox

JRadioButton

JComboBox

JList

JSlider

JTextComponent

JLabel

JButton

Component Container JComponent

JTextField

JTextArea

JScrollBar

Page 4: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

4

java.awt.Container

+add(comp: Component): Component

+add(comp: Component, index: int): Component

+remove(comp: Component): void

+getLayout(): LayoutManager

+setLayout(l: LayoutManager): void

+paintComponents(g: Graphics): void

Appends a component to the container.

Adds a component to the container with the specified index.

Removes the component from the container.

Returns the layout manager for this container.

Sets the layout manager for this container.

Paints each of the components in this container.

java.awt.Component

+getFont(): java.awt.Font

+setFont(f: java.awt.Font): void

+getBackground(): java.awt.Color

+setBackground(c: Color): void

+getForeground(): java.awt.Color

+setForeground(c: Color): void

+getWidth(): int

+getHeight(): int

+getPreferredSize(): Dimension

+setPreferredSize(d: Dimension) : void

+isVisible(): boolean

+setVisible(b: boolean): void

Returns the font of this component.

Sets the font of this component.

Returns the background color of this component.

Sets the background color of this component.

Returns the foreground color of this component.

Sets the foreground color of this component.

Returns the width of this component.

Returns the height of this component.

Returns the preferred size of this component.

Sets the preferred size of this component.

Indicates whether this component is visible.

Shows or hides this component.

javax.swing.JComponent

+getToolTipText(): String

+setToolTipText(test: String): void

+getBorder(): javax.swing.border.Border

+setBorder(border: Border): void

Returns the tool tip text for this component. Tool tip text is displayed when the mouse points on the component without clicking.

Sets a new tool tip text for this component.

Returns the border for this component.

Sets a new border for this component.

Page 5: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

5

BordersYou 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 message panel:

JPanel panel = new JPanel();panel.setBorder(new TitleBorder(“My Panel”);

Page 6: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

6

Test Swing Common FeaturesComponent Properties

font background foreground preferredSize minimumSize maximumSize

JComponent Properties

toolTipTextdoubleBufferedborder

TestSwingCommonFeaturesTestSwingCommonFeatures RunRun

Page 7: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

7

ButtonsA 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.

Page 8: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

8

javax.swing.AbstractButton

+getActionCommand(): String

+setActionCommand(s: String): void

+getText(): String

+setText(text: String): void

+getIcon(): javax.swing.Icon

+setIcon(icon: Icon): void

+getPressedIcon(): javax.swing.Icon

+setPressedIcon(pressedIcon: Icon): void

+getRolloverIcon(): javax.swing.Icon

+setRolloverIcon(pressedIcon: Icon): void

+getMnemonic(): int

+setMnemonic(mnemonic: int): void

+getHorizontalAlignment(): int

+setHorizontalAlignment(alignment: int): void

+getHorizontalTextPosition(): int

+setHorizontalTextPosition(position: int): void

+getVerticalAlignment(): int

+setVerticalAlignment(vAlignment: int): void

+getVerticalTextPosition(): int

+setVerticalTextPosition(position: int) : void

+isBorderPainted(): Boolean

+setBorderPainted(b: boolean): void

+getIconTextGap(): int

+setIconTextGap(iconTextGap: int): void

+isSelected(): Boolean

+setSelected(b: boolean): void

Returns the action command of this button.

Sets a new action command for this button.

Returns the button’s text (i.e., the text label on the button).

Sets the button’s text.

Returns the button’s default icon.

Sets the button's default icon. This icon is also used as the "pressed" and "disabled" icon if there is no explicitly set pressed icon.

Returns the pressed icon (displayed when the button is pressed).

Sets a pressed icon for the button.

Returns the rollover icon (displayed when the mouse is over the button).

Sets a rollover icon for the button.

Returns the mnemonic key value of this button. You can select the button by pressing the ALT key and the mnemonic key at the same time.

Sets a mnemonic key value of this button.

Returns the horizontal alignment of the icon and text on the button.

Sets the horizontal alignment of the icon and text. (default: CENTER)

Returns the horizontal text position relative to the icon on the button.

Sets the horizontal text position of the text relative to the icon. (default: RIGHT)

Returns the vertical alignment of the icon and text on the button.

Sets the vertical alignment of the icon and text. (default: CENTER).

Returns the vertical text position relative to the icon on the button.

Sets the vertical text position of the text relative to the icon. (default: CENTER)

Indicates whether the border of the button is painted.

Draws or hides the border of the button. By default, a regular button’s border is painted, but the border for a check box and a radio button is not painted.

Returns the gap between the text and the icon on the button. (JDK 1.4)

Sets a gap between the text and the icon on the button. (JDK 1.4)

Returns the state of the button. True if the check box or radio button is selected, false if it's not.

Sets the state for the check box or radio button.

javax.swing.JComponent

Page 9: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

9

JButtonJButton inherits AbstractButton and provides several constructors to create buttons.

javax.swing.JButton

+JButton()

+JButton(icon: javax.swing.Icon)

+JButton(text: String)

+JButton(text: String, icon: Icon)

Creates a default button with no text and icon.

Creates a button with an icon.

Creates a button with text.

Creates a button with text and an icon.

javax.swing.AbstractButton

Page 10: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

10

JButton Constructors

The following are JButton constructors:

JButton()

JButton(String text)

JButton(String text, Icon icon)

JButton(Icon icon)

Page 11: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

11

JButton Properties text icon mnemonic horizontalAlignment verticalAlignment horizontalTextPosition verticalTextPosition iconTextGap

Page 12: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

12

IconsAn 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");

TestButtonIconsTestButtonIcons RunRun

Page 13: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

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

Page 14: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

14

Horizontal AlignmentsHorizontal 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.

Page 15: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

15

Vertical AlignmentsVertical 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.

Page 16: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

16

Horizontal Text PositionsHorizontal 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.

Page 17: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

17

Vertical Text PositionsVertical 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.

Page 18: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

18

Example 13.1: Using ButtonsWrite 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.

RunRun

ButtonDemoButtonDemo

JButton JButton

MessagePanel

Page 19: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

19

JCheckBoxJCheckBox 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.JCheckBox

+JCheckBox()

+JCheckBox(text: String)

+JCheckBox(text: String, selected: boolean)

+JCheckBox(icon: Icon)

+JCheckBox(text: String, icon: Icon)

+JCheckBox(text: String, icon: Icon, selected: boolean)

Creates a default check box button with no text and icon.

Creates a check box with text.

Creates a check box with text and specifies whether the check box is initially selected.

Creates a checkbox with an icon.

Creates a checkbox with text and an icon.

Creates a check box with text and an icon, and specifies whether the check box is initially selected.

javax.swing.AbstractButton

javax.swing.JToggleButton

Page 20: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

20

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.

CheckBoxDemoCheckBoxDemo RunRun

Page 21: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

21

JRadioButtonRadio buttons are variations of check boxes. They are often used in the group, where only one button is checked at a time.

javax.swing.JRadioButton

+JRadioButton()

+JRadioButton(text: String)

+JRadioButton(text: String, selected: boolean)

+JRadioButton(icon: Icon)

+JRadioButton(text: String, icon: Icon)

+JRadioButton(text: String, icon: Icon, selected: boolean)

Creates a default radio button with no text and icon.

Creates a radio button with text.

Creates a radio button with text and specifies whether the radio button is initially selected.

Creates a radio button with an icon.

Creates a radio button with text and an icon.

Creates a radio button with text and an icon, and specifies whether the radio button is initially selected.

javax.swing.AbstractButton

javax.swing.JToggleButton

Page 22: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

22

Grouping Radio Buttons

ButtonGroup btg = new ButtonGroup();

btg.add(jrb1);

btg.add(jrb2);

Page 23: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

23

Example 13.3: Using Radio ButtonsAdd three radio buttons named Red, Green, and Blue into the preceding example to let the user choose the color of the message.

RunRunRadioButtonDemoRadioButtonDemo

Page 24: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

24

JLabelA label is a display area for a short text, an image, or both.

javax.swing.JLabel

+JLabel()

+JLabel(icon: javax.swing.Icon)

+JLabel(icon: Icon, hAlignment: int)

+JLabel(text: String)

+JLabel(text: String, icon: Icon, hAlignment: int)

+JLabel(text: String, hAlignment: int)

+getText(): String

+setText(text: String): void

+getIcon(): javax.swing.Icon

+setIcon(icon: Icon): void

+getHorizontalAlignment(): int

+setHorizontalAlignment(alignment: int): void

+getHorizontalTextPosition(): int

+setHorizontalTextPosition(textPosition: int): void

+getVerticalAlignment(): int

+setVerticalAlignment(vAlignment: int): void

+getVerticalTextPosition(): int

+setVerticalTextPosition(vTextPosition: int) : void

+getIconTextGap(): int

+setIconTextGap(iconTextGap: int): void

Creates a default label with no text and icon.

Creates a label with an icon.

Creates a label with an icon and the specified horizontal alignment.

Creates a label with text.

Creates a label with text, an icon and the specified horizontal alignment.

Creates a label with text and the specified horizontal alignment.

Returns the label’s text.

Sets the label’s text.

Returns the label’s image icon.

Sets an image icon on the label.

Returns the horizontal alignment of the text and icon on the label.

Sets the horizontal alignment – same as for buttons.

Returns the horizontal text position relative to the icon on the label.

Sets the horizontal text position – same as for buttons.

Returns the vertical alignment of the text and icon on the label.

Sets the vertical alignment – same as for buttons.

Returns the vertical text position relative to the icon on the label.

Sets the vertical text position – same as for buttons

Returns the gap between the text and the icon on the label. (JDK 1.4)

Sets a gap between the text and the icon on the label. (JDK 1.4)

javax.swing.JComponent

Page 25: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

25

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)

Page 26: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

26

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.

Page 27: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

27

Using Labels// Create an image icon from image fileImageIcon icon = new ImageIcon("image/grapes.gif"); // Create a label with text, an icon, // with centered horizontal alignmentJLabel jlbl = new JLabel("Grapes", icon, SwingConstants.CENTER); // Set label's text alignment and gap between text and iconjlbl.setHorizontalTextPosition(SwingConstants.CENTER);jlbl.setVerticalTextPosition(SwingConstants.BOTTOM);jlbl.setIconTextGap(5);

Page 28: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

28

JTextFieldA text field is an input area where the usercan type in characters. Text fields are usefulin that they enable the user to enter in variable data (such as a name or a description).

javax.swing.JTextField

+JTextField()

+JTextField(column: int)

+JTextField(text: String)

+JTextField(text: String, columns: int)

+getColumns(): int

+setColumns(columns: int): void

+getHorizontalAlignment(): int

+setHorizontalAlignment(alignment: int): void

Creates a default empty text field with number of columns set to 0.

Creates an empty text field with specified number of columns.

Creates a text field initialized with the specified text.

Creates a text field initialized with the specified text and columns.

Returns the number of columns in this text field.

Sets the number of columns in this text field.

Returns the horizontal alignment of this text field.

Sets the horizontal alignment for this text field. (default: LEFT)

javax.swing.text.JTextComponent +getText(): String

+setText(text: String): void

+isEditable(): boolean

+setEditable(b: boolean): void

Returns the text contained in this text component.

Sets a text in this text component.

Indicates whether this text component is editable.

Sets the text component editable or prevents it from being edited. (default: true)

Page 29: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

29

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 thespecified text and the column size.

Page 30: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

30

JTextField PropertiestexthorizontalAlignmenteditablecolumns

Page 31: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

31

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.

Page 32: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

32

Example 13.4: Using Text FieldsAdd a text field to the preceding example to let the user set a new message.

RunRunTextFieldDemoTextFieldDemo

JFrame ButtonDemo CheckBoxDemo RadioButtonDemo TextFieldDemo

ActionListener

Page 33: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

33

JTextAreaIf 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.JTextArea

+JTextArea()

+JTextArea(rows: int, columns: int)

+JTextArea(text: String)

+JTextArea(text: String, rows: int, columns: int)

+append(s: String): void

+insert(s: String, pos: int): void

+replaceRange(s: String, start: int, end: int): void

+getColumns(): int

+setColumns(columns: int): void

+getRows(): int

+setRows(rows: int): void

+getLineCount(): int

+getTabSize(): int

+setTabSize(size: int): void

+getLineWrap(): Boolean

+setLineWrap(wrap: boolean): void

+getWrapStyleWord(): Boolean

+setWrapStyleWord(word: boolean): void

Creates a default empty text area.

Creates an empty text area with the specified number of rows and columns.

Creates a new text area with the specified text displayed.

Creates a new text area with the specified text and number of rows and columns.

Appends the string to text in the text area.

Inserts string s in the specified position in the text area.

Replaces partial text in the range from position start to end with string s.

Returns the number of columns in this text area.

Sets the number of columns in this text area.

Returns the number of rows in this text area.

Sets the number of rows in this text area.

Returns the actual number of lines contained in the text area.

Returns the number of characters used to expand tabs in this text area.

Sets the number of characters to expand tabs to. (default: 8)

Indicates whether the line in the text area is automatically wrapped.

Sets the line-wrapping policy of the text area. (default: false)

Indicates whether the line is wrapped on words or characters.

Sets the style of wrapping used if the text area is wrapping lines. The default value is false, which indicates that the line is wrapped on characters.

javax.swing.text.JTextComponent

Page 34: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

34

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 andthe number of rows and columns specified.

Page 35: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

35

JTextArea PropertiestexteditablecolumnslineWrapwrapStyleWordrowslineCounttabSize

Page 36: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

36

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.

DescriptionPanel -jlblImage: JLabel -jlblTitle: JLabel -jtaTextDescription: JTextArea +setImageIcon(icon: ImageIcon): void +setTitle(title: String): void +setTextDescription(text: String): void +getMinimumSize(): Dimension

1 TextAreaDemo

JPanel -char token +getToken +setToken +paintComponet +mouseClicked

JFrame -char token +getToken +setToken +paintComponet +mouseClicked

1

Page 37: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

37

Example 13.5, cont.

RunRunTextAreaDemoTextAreaDemo

Page 38: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

38

JComboBoxA 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.JComboBox

+JComboBox()

+JComboBox(items: Object[])

+addItem(item: Object): void

+getItemAt(index: int): Object

+getItemCount(): int

+getSelectedIndex(): int

+setSelectedIndex(index: int): void

+getSelectedItem(): Object

+setSelectedItem(item: Object): void

+removeItem(anObject: Object): void

+removeItemAt(anIndex: int): void

+removeAllItems(): void

Creates a default empty combo box.

Creates a combo box that contains the elements in the specified array.

Adds an item to the combo box.

Returns the item at the specified index.

Returns the number of items in the combo box.

Returns the index of the selected item.

Sets the selected index in the combo box.

Returns the selected item.

Sets the selected item in the combo box.

Removes an item from the item list.

Removes the item at the specified index in the combo box.

Removes all items in the combo box.

javax.swing.JComponent

Page 39: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

39

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

Page 40: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

40

Using theitemStateChanged 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.

Page 41: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

41

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.

RunRunComboBoxDemoComboBoxDemo

Page 42: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

42

JListA 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.JList

+JList()

+JList(items: Object[])

+getSelectedIndex(): int

+setSelectedIndex(index: int): void

+getSelectedIndices(): int[]

+setSelectedIndices(indices: int[]): void

+getSelectedValue(): Object

+getSelectedValues(): Object[]

+getVisibleRowCount(): int

+setVisibleRowCount(count: int): void

+getSelectionBackground(): Color

+setSelectionBackground(c: Color): void

+getSelectionForeground(): Color

+setSelectionForeground(c: Color): void

+getSelectionMode(): int

+setSelectionMode(selectionMode: int):

Creates a default empty list.

Creates a list that contains the elements in the specified array.

Returns the index of the first selected item.

Selects the cell at the specified index.

Returns an array of all of the selected indices in increasing order.

Selects the cells at the specified indices.

Returns the first selected item in the list.

Returns an array of the values for the selected cells in increasing index order.

Returns the number of visible rows displayed without a scrollbar. (default: 8)

Sets the preferred number of visible rows displayed without a scrollbar.

Returns the background color of the selected cells.

Sets the background color of the selected cells.

Returns the foreground color of the selected cells.

Sets the foreground color of the selected cells.

Returns the selection mode for the list.

Sets the selection mode for the list.

javax.swing.JComponent

Page 43: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

43

JList Constructors JList()

Creates an empty list.

JList(Object[] stringItems)

Creates a new list initialized with items.

Page 44: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

44

JList Properties

selectedIndexd

selectedIndices

selectedValue

selectedValues

selectionMode

visibleRowCount

Page 45: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

45

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.

RunRunListDemoListDemo

Page 46: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

46

JScrollBarA 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.JScrollBar

+JScrollBar()

+JScrollBar(orientation: int)

+JScrollBar(orientation: int, value: int, extent: int, min: int, max: int)

+getBlockIncrement(): int

+setBlockIncrement(increment: int): void

+getMaximum(): int

+setMaximum(maximum: int): void

+getMinimum(): int

+setMinimum(minimum: int): void

+getOrientation(): int

+setOrientation(orientation: int): void

+getUnitIncrement(): int

+setUnitIncrement(increment: int): void

+getValue(): int

+setValue(int value): void

+getVisibleAmount(): int

+setVisibleAmount(extent: int): void

Creates a default vertical scroll bar.

Creates a scroll bar with the specified orientation.

Creates a scrollbar with the specified orientation, value, extent, minimum, and maximum.

Returns the block increment.

Sets a new block increment. (default: 10)

Returns the maximum value represented by the scroll bar.

Sets a new maximum. (default: 100)

Returns the minimum value represented by the scroll bar.

Sets a new minimum. (default: 0)

Returns the orientation of the scroll bar.

Sets a new orientation for the scroll bar.

Returns the unit increment in the scroll bar.

Sets a new unit increment in the scroll bar.

Returns the current value represented by the scroll bar.

Sets a new current value represented by the scroll bar.

Returns the visible amount in the scroll bar.

Sets a new visible amount for the scroll bar. (default: 10)

javax.swing.JComponent

Page 47: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

47

Scroll Bar Properties

Bubble

Unit increment

Block decrement Block increment

Minimal value Maximal value

Unit decrement

Page 48: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

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.

ScrollBarDemoScrollBarDemo RunRun

Page 49: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

49

JSliderJSlider is similar to JScrollBar, but JSlider has more properties and can appear in many forms.

javax.swing.JSlider

+JSlider()

+JSlider(min: int, max: int)

+JSlider(min: int, max: int, value: int)

+JSlider(orientation: int)

+JSlider(orientation: int, min: int, max: int, value: int)

+getInverted(): boolean

+setInverted(b: boolean): void

+getMajorTickSpacing(): int

+setMajorTickSpacing(n: int): void

+getMinorTickSpacing(): int

+setMinorTickSpacing(n: int): void

+getMaximum(): int

+setMaximum(maximum: int): void

+getMinimum(): int

+setMinimum(minimum: int): void

+getOrientation(): int

+setOrientation(orientation: int): void

+getPaintLabels(): boolean

+setPaintLabels(b: boolean): void

+getPaintTicks(): boolean

+setPaintTicks(b: boolean): void

+getPaintTrack(): boolean

+setPaintTrack(b: boolean): void

+getValue(): int

+setValue(int value): void

Creates a default horizontal slider.

Creates a horizontal slider using the specified min and max.

Creates a horizontal slider using the specified min, max, and value.

Creates a slider with the specified orientation.

Creates a slider with the specified orientation, min, max, and value.

Returns true if the value-range shown for the slider is reversed.

Sets true to reverse the value-range, and false to put the value range in the normal order. (default: false)

Returns the number of units between major ticks.

Sets the number of units between major ticks. (default: 0)

Returns the number of units between minor ticks.

Sets the number of units between minor ticks. (default: 0)

Returns the maximum value represented by the slider.

Sets a new maximum. (default: 100)

Returns the minimum value represented by the slider.

Sets a new minimum. (default: 0)

Returns the orientation of the slider.

Sets a new orientation for the slider.

Returns true if the labels are painted at tick marks.

Sets a Boolean value to determine whether labels are painted. (default: false)

Returns true if the ticks are painted on the slider.

Sets a Boolean value to determine whether ticks are painted. (default: false)

Returns true if the track are painted on the slider.

Sets a Boolean value to determine whether tracks are painted. (default: true)

Returns the current value represented by the slider.

Sets a new value represented by the slider.

javax.swing.JComponent

Page 50: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

50

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.

SliderDemoSliderDemo RunRun

Page 51: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

51

Creating Multiple Windows

The following slides show step-by-step how to create an additional window from an application or applet.

Page 52: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

52

Step 1: Create a subclass of JFrame (called a SubFrame) that tells the new window whatto do. For example, all the GUI application programs extend JFrame and are subclassesof JFrame.

Creating Additional Windows, Step 1

Page 53: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

53

Creating Additional Windows, Step 2

Step 2: Create an instance of SubFrame in the application or applet.

Example:

SubFrame subFrame = new

SubFrame("SubFrame Title");

Page 54: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

54

Creating Additional Windows, Step 3

Step 3: Create a JButton for activating the subFrame.

add(new JButton("Activate SubFrame"));

Page 55: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

55

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

Page 56: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

56

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.

Page 57: 1 Chapter 13 Creating User Interfaces. 2 Objectives F To create graphical user interfaces with various user-interface components: JButton, JCheckBox,

57

Example 13.10, cont.

RunRunMultipleWindowsDemoMultipleWindowsDemo

HistogramHistogram