Professional Documents
Culture Documents
Lecturer: Dr. JAMAL-DEEN ADBULAI:, CSCD Contact Information: Jabdulai@ug - Edu.gh
Lecturer: Dr. JAMAL-DEEN ADBULAI:, CSCD Contact Information: Jabdulai@ug - Edu.gh
Lecturer: Dr. JAMAL-DEEN ADBULAI:, CSCD Contact Information: Jabdulai@ug - Edu.gh
College of Education
School of Continuing and Distance Education
2014/2015 – 2016/2017
Session Objectives
• Understand and be able to distinguish between Swing and
AWT
• Be able to describe the Java GUI API hierarchy
• Understand the role of layout managers
• Be able to create listeners for various types of events
• Be able to implement JButton, JCheckbox, JRadioButton,
JLabel, JTextField, JComboBox, JList, JTextArea
CONTAINER CLASSES
16
Kinds of Layout Managers
• FlowLayout
• GridLayout
• BorderLayout
17
FlowLayout Example
18
The FlowLayout Class
The get and set methods for these data fields are provided in
java.awt.FlowLayout the class, but omitted in the UML diagram for brevity.
19
GridLayout Example
20
The GridLayout Class
The get and set methods for these data fields are provided in
java.awt.GridLayout the class, but omitted in the UML diagram for brevity.
-rows: int The number of rows in this layout manager (default: 1).
-columns: int The number of columns in this layout manager (default: 1).
-hgap: int The horizontal gap of this layout manager (default: 0).
-vgap: int The vertical gap of this layout manager (default: 0).
21
The BorderLayout Manager
22
BorderLayout Example
23
The BorderLayout Class
The get and set methods for these data fields are provided in
java.awt.BorderLayout the class, but omitted in the UML diagram for brevity.
-hgap: int The horizontal gap of this layout manager (default: 0).
-vgap: int The vertical gap of this layout manager (default: 0).
24
The Color Class
Example:
Color c = new Color(228, 100, 255);
25
Standard Colors
26
Setting Colors
You can use the following methods to set the
component’s background and foreground colors:
setBackground(Color c)
setForeground(Color c)
Example:
jbt.setBackground(Color.yellow);
jbt.setForeground(Color.red);
27
The Font Class
Font Names Font Style
Standard font names Font.PLAIN (0),
that are supported in Font.BOLD (1),
all platforms are: Font.ITALIC (2), and
SansSerif, Serif, Font.BOLD +
Monospaced, Dialog, Font.ITALIC (3)
or DialogInput.
28
Finding All Available Font Names
GraphicsEnvironment e =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames =
e.getAvailableFontFamilyNames();
for (int i = 0; i < fontnames.length; i++)
System.out.println(fontnames[i]);
29
Using Panels as Sub-Containers
30
Creating a JPanel
frame
A textfield
p2
A button 12
buttons p1
32
Common Features of Swing Components
The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
java.awt.Component
-font: java.awt.Font The font of this component.
-background: java.awt.Color The background color of this component.
-foreground: java.awt.Color The foreground color of this component.
-preferredSize: Dimension The preferred size of this component.
-visible: boolean Indicates whether this component is visible.
+getWidth(): int Returns the width of this component.
+getHeight(): int Returns the height of this component.
+getX(): int getX() and getY() return the coordinate of the component’s
+getY(): int upper-left corner within its parent component.
java.awt.Container
+add(comp: Component): Component Adds a component to the container.
+add(comp: Component, index: int): Component Adds a component to the container with the specified index.
+remove(comp: Component): void Removes the component from the container.
+getLayout(): LayoutManager Returns the layout manager for this container.
+setLayout(l: LayoutManager): void Sets the layout manager for this container.
+paintComponents(g: Graphics): void Paints each of the components in this container.
The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
javax.swing.JComponent
-toolTipText: String The tool tip text for this component. Tool tip text is displayed when
33
the mouse points on the component without clicking.
-border: javax.swing.border.Border The border for this component.
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”));
34
Image Icons
GUI COMPONENTS
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.
39
JButton Constructors and Properties
• The following are JButton constructors:
JButton()
JButton(String text)
JButton(String text, Icon icon)
JButton(Icon icon)
• Jbutton properties:
• Text, icon, mnemonic, horizontalAlignment,
verticalAlignment,
horizontalTextPosition,
verticalTextPosition, iconTextGap
40
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 not pressed.
42
Vertical Alignments
43
Horizontal Text Positions
44
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.
45
Example: Using Buttons
MessagePanel
JButton JButton
46
JCheckBox
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: Creates a check box with text and specifies whether the check box is
boolean) 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, Creates a check box with text and an icon, and specifies whether the check
selected: boolean) box is initially selected.
47
Example: Using Check Boxes
48
JRadioButton
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: Creates a radio button with text and specifies whether the radio button is
boolean) 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, Creates a radio button with text and an icon, and specifies whether the radio
selected: boolean) button is initially selected.
49
Grouping Radio Buttons
50
Example: Using Radio Buttons
51
JLabel
javax.swing.JComponent
The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
javax.swing.JLabel
-text: String The label’s text.
-icon: javax.swing.Icon The label’s image icon.
-horizontalAlignment: int The horizontal alignment of the text and icon on the label.
-horizontalTextPosition: int The horizontal text position relative to the icon on the label.
-verticalAlignment: int The vertical alignment of the text and icon on the label.
-verticalTextPosition: int The vertical text position relative to the icon on the label.
-iconTextGap: int The gap between the text and the icon on the label (JDK 1.4).
+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, Creates a label with text, an icon, and the specified horizontal alignment.
hAlignment: int)
+JLabel(text: String, hAlignment: int) Creates a label with text and the specified horizontal alignment.
52
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)
53
JLabel Properties
54
Using Labels
// Set label's text alignment and gap between text and icon
jlbl.setHorizontalTextPosition(SwingConstants.CENTER);
jlbl.setVerticalTextPosition(SwingConstants.BOTTOM);
jlbl.setIconTextGap(5);
55
JTextField
The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
javax.swing.text.JTextComponent
-text: String The text contained in this text component.
-editable: boolean Indicates whether this text component is editable (default: true).
javax.swing.JTextField
-columns: int The number of columns in this text field.
-horizontalAlignment: int The horizontal alignment of this text field (default: LEFT).
+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.
56
JTextField Constructors
• JTextField(int columns)
Creates an empty text field with the specified
number of columns.
• JTextField(String text)
Creates a text field initialized with the specified text.
• JTextField(String text, int columns)
Creates a text field initialized with the
specified text and the column size.
57
JTextField Properties
• text
• horizontalAlignment
• editable
• columns
58
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.
59
Example: Using Text Fields
60
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 The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
javax.swing.JTextArea
-columns: int The number of columns in this text area.
-rows: int The number of rows in this text area.
-tabSize: int The number of characters used to expand tabs (default: 8).
-lineWrap: boolean Indicates whether the line in the text area is automatically wrapped (default:
false).
-wrapStyleWord: boolean Indicates whether the line is wrapped on words or characters (default: false).
+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): Replaces partial text in the range from position start to end with string s.
void
+getLineCount(): int Returns the actual number of lines contained in the text area.
61
JTextArea Constructors
• JTextArea(int rows, int columns)
Creates a text area with the specified number of
rows and columns.
62
JTextArea Properties
• text
• editable
• columns
• lineWrap
• wrapStyleWord
• rows
• lineCount
• tabSize
63
Example: Using Text Areas
64
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.
+removeItemAt(anIndex: int): void Removes the item at the specified index in the combo box.
+removeAllItems(): void Removes all items in the combo box.
65
JComboBox Methods
66
Using the itemStateChanged Handler
67
Example: Using Combo Boxes
68
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.
+setSelectionMode(selectionMode: int): Sets the selection mode for the list.
69
JList Constructors
• JList()
• JList(Object[] stringItems)
Creates a new list initialized with items.
70
JList Properties
• selectedIndexd
• selectedIndices
• selectedValue
• selectedValues
• selectionMode
• visibleRowCount
71
Example: Using Lists
72
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
The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
javax.swing.JScrollBar
-orientation: int Specifies horizontal or vertical style, default is horizontal.
-maximum: int Specifies the maximum value the scroll bar represents when the bubble
reaches the right end of the scroll bar for horizontal style or the
bottom of the scroll bar for vertical style.
-minimum: int Specifies the minimum value the scroll bar represents when the bubble
reaches the left end of the scroll bar for horizontal style or the top of
the scroll bar for vertical style.
-visibleAmount: int Specifies the relative width of the scroll bar's bubble. The actual width
appearing on the screen is determined by the maximum value and the
value of visibleAmount.
-value: int Represents the current value of the scroll bar.
-blockIncrement: int Specifies value added (subtracted) when the user activates the block-
increment (decrement) area of the scroll bar, as shown in Figure
13.30.
-unitIncrement: int Specifies the value added (subtracted) when the user activates the unit-
increment (decrement) area of the scroll bar, as shown in Figure
13.30.
73
Scroll Bar Properties
Bubble
Unit decrement Unit increment
74
Example: 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.
75
JSlider
JSlider is similar to JScrollBar, but JSlider has more
properties and can appear in many forms.
javax.swing.JComponent
The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
javax.swing.JSlider
-maximum: int The maximum value represented by the slider (default: 100).
-minimum: int The minimum value represented by the slider (default: 0).
-value: int The current value represented by the slider.
-orientation: int The orientation of the slider (default: JSlider.HORIZONTAL).
-paintLabels: boolean True if the labels are painted at tick marks (default: false).
-paintTicks: boolean True if the ticks are painted on the slider (default: false).
-paintTrack: boolean True if the track is painted on the slider (default: true).
-majorTickSpacing: int The number of units between major ticks (default: 0).
-minorTickSpacing: int The number of units between minor ticks (default: 0).
-inverted: boolean True to reverse the value-range, and false to put the value range in the
normal order (default: false).
+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: Creates a slider with the specified orientation, min, max, and value.
int, value: int)
76
Example: Using Sliders
77
References
• Big Java Late Objects (Horstmann, 2012)
• An Introduction to Problem Solving and Programming
(Savitch, 2012)
• Introduction to Java Programming(Liang, 2011)