liang,introduction to java programming,revised by dai-kaiyu 1 chapter 13 creating user interfaces...
TRANSCRIPT
Liang,Introduction to Java Programming,revised by Dai-kaiyu1
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
…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-kaiyu2
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-kaiyu3
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu4
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu5
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 panel:
JPanel panel = new JPanel();panel.setBorder(new TitleBorder(“My Panel”));
Liang,Introduction to Java Programming,revised by Dai-kaiyu6
Test Swing Common Features
Component Properties
font background foreground preferredSize minimumSize maximumSize
JComponent Properties
toolTipTextborder
TestSwingCommonFeaturesTestSwingCommonFeatures RunRun
Liang,Introduction to Java Programming,revised by Dai-kaiyu7
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu8
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu9
JButton
JButton 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
Liang,Introduction to Java Programming,revised by Dai-kaiyu10
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-kaiyu11
JButton Properties
text icon mnemonic horizontalAlignment verticalAlignment horizontalTextPosition verticalTextPosition iconTextGap
Liang,Introduction to Java Programming,revised by Dai-kaiyu12
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu13
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-kaiyu14
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.
See figure 13.7
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu15
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu16
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu17
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.
RunRun
ButtonDemoButtonDemo
JButton JButton
MessagePanel
setMnemonic (using alt key)
getSource() to judge the source UI
Liang,Introduction to Java Programming,revised by Dai-kaiyu18
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu19
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
ButtonDemo
CheckBoxDemo
Liang,Introduction to Java Programming,revised by Dai-kaiyu20
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu21
Grouping Radio Buttons
ButtonGroup btg = new ButtonGroup();
btg.add(jrb1);
btg.add(jrb2);
Liang,Introduction to Java Programming,revised by Dai-kaiyu22
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.
RunRunRadioButtonDemoRadioButtonDemo
ButtonDemo
CheckBoxDemo
RadioButtonDemo
Liang,Introduction to Java Programming,revised by Dai-kaiyu23
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu24
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-kaiyu25
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-kaiyu26
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);
Liang,Introduction to Java Programming,revised by Dai-kaiyu27
JTextField
A 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)
Liang,Introduction to Java Programming,revised by Dai-kaiyu28
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu29
JTextField Properties
texthorizontalAlignmenteditablecolumns
Liang,Introduction to Java Programming,revised by Dai-kaiyu30
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-kaiyu31
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
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-kaiyu32
JTextAreaJTextAreaenables 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
Liang,Introduction to Java Programming,revised by Dai-kaiyu33
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu34
JTextArea Properties
texteditablecolumnslineWrapwrapStyleWordrowslineCounttabSize
Liang,Introduction to Java Programming,revised by Dai-kaiyu35
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu36
Example 13.5, cont.
RunRunTextAreaDemoTextAreaDemo
Liang,Introduction to Java Programming,revised by Dai-kaiyu37
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu38
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-kaiyu39
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu40
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu41
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu42
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-kaiyu43
JList Properties
selectedIndexd
selectedIndices
selectedValue
selectedValues
selectionMode
visibleRowCount
Liang,Introduction to Java Programming,revised by Dai-kaiyu44
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
Jlabel.setIcon(null);
Liang,Introduction to Java Programming,revised by Dai-kaiyu45
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu46
Scroll Bar Properties
Bubble
Unit increment
Block decrement Block increment
Minimal value Maximal value
Unit decrement
Liang,Introduction to Java Programming,revised by Dai-kaiyu47
Scroll Bar event-driven model
JScrollBar
Change the value of Generate AdjustmentEvent
AdjustmentListenerregister
adjustmentValueChanged
Liang,Introduction to Java Programming,revised by Dai-kaiyu48
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu49
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu50
Scroll Bar event-driven model
JSlider
Change the value of Generate ChangedEvent
ChangeListenerregister
stateChanged
Liang,Introduction to Java Programming,revised by Dai-kaiyu51
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
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-kaiyu52
Liang,Introduction to Java Programming,revised by Dai-kaiyu53
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-kaiyu54
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
Liang,Introduction to Java Programming,revised by Dai-kaiyu55
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-kaiyu56
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-kaiyu57
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-kaiyu58
Example 13.10 Creating Multiple WindowsThis 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-kaiyu59
Example 13.10, cont.
RunRunMultipleWindowsDemoMultipleWindowsDemo
HistogramHistogram
Liang,Introduction to Java Programming,revised by Dai-kaiyu60
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-kaiyu 61
1 // Fig. 13.10: MenuTest.java2 // Demonstrating menus3 4 // Java core packages5 import java.awt.*;6 import java.awt.event.*;7 8 // Java extension packages9 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 GUI22 public MenuTest()23 {24 super( "Using JMenus" ); 25 26 // set up File menu and its menu items27 JMenu fileMenu = new JMenu( "File" );28 fileMenu.setMnemonic( 'F' );29 30 // set up About... menu item31 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
Liang,Introduction to Java Programming,revised by Dai-kaiyu 62
36 // anonymous inner class to handle menu item event37 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 class48 49 ); // end call to addActionListener50 51 fileMenu.add( aboutItem );52 53 // set up Exit menu item54 JMenuItem exitItem = new JMenuItem( "Exit" );55 exitItem.setMnemonic( 'x' );56 57 exitItem.addActionListener(58 59 // anonymous inner class to handle exitItem event60 new ActionListener() {61 62 // terminate application when user clicks exitItem63 public void actionPerformed( ActionEvent event )64 {65 System.exit( 0 );66 }67 68 } // end anonymous inner class69 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
Liang,Introduction to Java Programming,revised by Dai-kaiyu 63
71 72 fileMenu.add( exitItem );73 74 // create menu bar and attach it to MenuTest window75 JMenuBar bar = new JMenuBar(); 76 setJMenuBar( bar ); 77 bar.add( fileMenu ); 78 79 // create Format menu, its submenus and menu items80 JMenu formatMenu = new JMenu( "Format" ); 81 formatMenu.setMnemonic( 'r' );82 83 // create Color submenu84 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 items94 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 item105 colorItems[ 0 ].setSelected( true );
Instantiate JMenuBar to contain JMenus
Instantiate Format JMenu
Instantiate Color JMenu (submenu of Format JMenu)
Instantiate JRadioButtonMenuItems for Color JMenu and ensure that only one menu item is selected at a time
Liang,Introduction to Java Programming,revised by Dai-kaiyu 64
106 107 // add format menu to menu bar108 formatMenu.add( colorMenu );109 formatMenu.addSeparator();110 111 // create Font submenu112 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 items121 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 item132 fonts[ 0 ].setSelected( true );133 134 fontMenu.addSeparator();135 136 // set up style menu items137 String styleNames[] = { "Bold", "Italic" };138 139 styleItems = new JCheckBoxMenuItem[ styleNames.length ];140 StyleHandler styleHandler = new StyleHandler();
Separator places line between JMenuItems
Instantiate Font JMenu (submenu of Format JMenu)
Instantiate JRadioButtonMenuItems for Font JMenu and ensure that only one menu item is selected at a time
Liang,Introduction to Java Programming,revised by Dai-kaiyu 65
141 142 // create style checkbox menu items143 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 menu153 formatMenu.add( fontMenu );154 155 // add Format menu to menu bar156 bar.add( formatMenu ); 157 158 // set up label to display text159 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 constructor172
Liang,Introduction to Java Programming,revised by Dai-kaiyu 66
173 // execute application174 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 items183 private class ItemHandler implements ActionListener {184 185 // process color and font selections186 public void actionPerformed( ActionEvent event )187 {188 // process color selection189 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 selection197 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 }204205 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 67
208 } // end class ItemHandler209210 // inner class to handle item events from check box menu items211 private class StyleHandler implements ItemListener {212213 // process font style selections214 public void itemStateChanged( ItemEvent e )215 {216 style = 0;217 218 // check for bold selection219 if ( styleItems[ 0 ].isSelected() )220 style += Font.BOLD;221222 // check for italic selection223 if ( styleItems[ 1 ].isSelected() )224 style += Font.ITALIC;225226 displayLabel.setFont( new Font( 227 displayLabel.getFont().getName(), style, 72 ) );228229 repaint();230 }231232 } // end class StyleHandler233234 } // end class MenuTest
Invoked when user selects JCheckBoxMenuItem
Determine new font style
Liang,Introduction to Java Programming,revised by Dai-kaiyu 68
MenuTest.java
Program Output