Lecturer: Dr. JAMAL-DEEN ADBULAI:, CSCD Contact Information: Jabdulai@ug - Edu.gh

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 78

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

Dr. JAMAL-DEEN ADBULAI, CSCD Slide 2


Session Outline
The key topics to be covered in the session are as follows:
• Java GUI basics
• Container Classes
• GUI Helper Classes
• GUI Components

Dr. JAMAL-DEEN ADBULAI, CSCD Slide 3


Reading List
• Chapters 12 and 17 of Text - Introduction to Java
Programming(Liang, 2011)

Dr. JAMAL-DEEN ADBULAI, CSCD Slide 4


Topic One

JAVA GUI BASICS

Dr. JAMAL-DEEN ADBULAI, CSCD Slide 5


Introduction
• A graphical user interface (GUI) makes a system user
friendly and easy to use.
• Creating a GUI requires creativity and knowledge of how
GUI components work.
• Since the GUI components in Java are very flexible and
versatile, you can create a wide assortment of useful user
interfaces.
• Two libraries exist: Swing and AWT (Abstract Window
Toolkit)
• Swing GUI components are frequently used to create user
interfaces in Java.
Dr. JAMAL-DEEN ADBULAI, CSCD Slide 6
Swing vs. AWT
• AWT is fine for developing simple graphical user interfaces,
but not for developing comprehensive GUI projects.
• AWT is prone to platform-specific bugs.
• Swing components depend less on the target platform and
use less of the native GUI resource.
• Swing components that don’t rely on native GUI are
referred to as lightweight components
• AWT components are referred to as heavyweight
components.
• the Swing GUI component classes are named with a
prefixed J.
• Focus will be on using Swing GUI.
Dr. JAMAL-DEEN ADBULAI, CSCD Slide 7
AWT Components

Dr. JAMAL-DEEN ADBULAI, CSCD Slide 8


Swing Components

Dr. JAMAL-DEEN ADBULAI, CSCD Slide 9


Topic Two

CONTAINER CLASSES

Dr. JAMAL-DEEN ADBULAI, CSCD Slide 10


Container Classes
• Container classes are GUI components that are used to
contain other GUI components.
• Window, Panel, Applet, Frame, and Dialog are the
container classes for AWT components.
• To work with Swing components, use Container, JFrame,
JDialog, JApplet, and JPanel

Dr. JAMAL-DEEN ADBULAI, CSCD Slide 11


Creating Frames
import javax.swing.*;
public class MyFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("Test Frame");
frame.setSize(400, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
}
}
Dr. JAMAL-DEEN ADBULAI, CSCD Slide 12
Adding Components into a Frame
• // Add a button into the frame
frame.add( new JButton("OK"));

Dr. JAMAL-DEEN ADBULAI, CSCD Slide 13


JFrame Class
javax.swing.JFrame Creates a default frame with no title.
+JFrame() Creates a frame with the specified title.
+JFrame(title: String) Specifies the size of the frame.
+setSize(width: int, height: int): void Specifies the upper-left corner location of
+setLocation(x: int, y: int): void the frame.
+setVisible(visible: boolean): void Sets true to display the frame.
+setDefaultCloseOperation(mode: Specifies the operation when the frame is
int): void closed.
+setLocationRelativeTo(c: Sets the location of the frame relative to
Component): void the specified component. If the
+pack(): void component is null, the frame is centered
on the screen.
Automatically sets the frame size to hold
the components in the frame.

Dr. JAMAL-DEEN ADBULAI, CSCD Slide 14


Topic Three

GUI HELPER CLASSES

Dr. JAMAL-DEEN ADBULAI, CSCD Slide 15


Layout Managers
• Java’s layout managers provide a level of abstraction to
automatically map your user interface on all window
systems.

• The UI components are placed in containers. Each


container has a layout manager to arrange the UI
components within the container.

• Layout managers are set in containers using the


setLayout(LayoutManager) method in a container.

16
Kinds of Layout Managers
• FlowLayout

• GridLayout

• BorderLayout

• Several other layout managers exist

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.

-alignment: int The alignment of this layout manager (default: CENTER).


-hgap: int The horizontal gap of this layout manager (default: 5 pixels).
-vgap: int The vertical gap of this layout manager (default: 5 pixels).

+FlowLayout() Creates a default FlowLayout manager.


+FlowLayout(alignment: int) Creates a FlowLayout manager with a specified alignment.
+FlowLayout(alignment: int, hgap: Creates a FlowLayout manager with a specified alignment,
int, vgap: int) horizontal gap, and vertical gap.

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

+GridLayout() Creates a default GridLayout manager.


+GridLayout(rows: int, columns: int) Creates a GridLayout with a specified number of rows and columns.
+GridLayout(rows: int, columns: int, Creates a GridLayout manager with a specified number of rows and
hgap: int, vgap: int) columns, horizontal gap, and vertical gap.

21
The BorderLayout Manager

The BorderLayout add(Component,


manager divides the constraint), where
container into five areas: constraint is
East, South, West, North, BorderLayout.EAST,
and Center. Components BorderLayout.SOUTH,
are added to a BorderLayout.WEST,
BorderLayout by using
BorderLayout.NORTH, or
the add method.
BorderLayout.CENTER.

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

+BorderLayout() Creates a default BorderLayout manager.


+BorderLayout(hgap: int, vgap: int) Creates a BorderLayout manager with a specified number of
horizontal gap, and vertical gap.

24
The Color Class

• You can set colors for GUI components by using the


java.awt.Color class.

• Colors are made of red, green, and blue components, each


of which is represented by a byte value that describes its
intensity, ranging from 0 (darkest shade) to 255 (lightest
shade). This is known as the RGB model.
Color c = new Color(r, g, b);
r, g, and b specify a color by its red, green, and blue
components.

Example:
Color c = new Color(228, 100, 255);
25
Standard Colors

• Thirteen standard colors (black, blue, cyan, darkGray,


gray, green, lightGray, magenta, orange, pink, red,
white, yellow) are defined as constants in
java.awt.Color.

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.

Font myFont = new Font(name, style, size);


Example:
Font myFont = new Font("SansSerif ", Font.BOLD, 16);
Font myFont = new Font("Serif", Font.BOLD+Font.ITALIC, 12);

JButton jbtOK = new JButton("OK“);


jbtOK.setFont(myFont);

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

• Panels act as sub-containers for grouping user


interface components.
• It is recommended that you place the user interface
components in panels and place the panels in a frame.
You can also place panels in a panel.
• To add a component to JFrame, you actually add it to
the content pane of JFrame. To add a component to a
panel, you add it directly to the panel using the add
method.

30
Creating a JPanel

• You can use new JPanel() to create a panel with a


default FlowLayout manager or new
JPanel(LayoutManager) to create a panel with the
specified layout manager.
• Use the add(Component) method to add a component
to the panel. For example,

JPanel p = new JPanel();


p.add(new JButton("OK"));
31
Testing Panels Example
This example uses panels to organize components. The
program creates a user interface for a Microwave oven.

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

• Java uses the javax.swing.ImageIcon class to represent an


icon.
• An icon is a fixed-size picture; typically it is small and used
to decorate components.
• Images are normally stored in image files.
• You can use
new ImageIcon(filename)
to construct an image icon.
• For example, the following statement creates an icon from
an image file us.gif in the image directory under the
current class path:
ImageIcon icon = new ImageIcon("image/us.gif");
35
Splash Screen
• A splash screen is an image that is displayed while the
application is starting up.
• If your program takes a long time to load, you may
display a splash screen to alert the user. For example,
the following command:

java –splash:image/us.gf TestImageIcon

displays an image while the program TestImageIcon is


being loaded.
36
Topic Four

GUI COMPONENTS

Dr. JAMAL-DEEN ADBULAI, CSCD Slide 37


Buttons
• A button is a component that triggers an action event when
clicked.
• Swing provides regular buttons, toggle buttons, check box
buttons, and radio buttons.
• The common features of these buttons are defined in
javax.swing. AbstractButton

Dr. JAMAL-DEEN ADBULAI, CSCD Slide 38


JButton

JButton inherits AbstractButton and provides several


constructors to create buttons.

javax.swing.AbstractButton

javax.swing.JButton
+JButton() Creates a default button with no text and icon.
+JButton(icon: javax.swing.Icon) Creates a button with an icon.
+JButton(text: String) Creates a button with text.
+JButton(text: String, icon: Icon) Creates a button with text and an icon.

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.

(A) Default icon (B) Pressed icon (C) Rollover icon


41
Horizontal Alignments
• Horizontal alignment specifies how the icon and text are
placed horizontally on a button.
• You can set the horizontal alignment using one of the five
constants: LEADING, LEFT, CENTER, RIGHT, TRAILING. At
present, LEADING and LEFT are the same and TRAILING
and RIGHT are the same.
• The default horizontal alignment is
SwingConstants.TRAILING.

42
Vertical Alignments

• Vertical alignment specifies how the icon and text are


placed vertically on a button.
• You can set the vertical alignment using one of the three
constants: TOP, CENTER, BOTTOM.
• The default vertical alignment is SwingConstants.CENTER.

43
Horizontal Text Positions

• Horizontal text position specifies the horizontal position


of the text relative to the icon.
• You can set the horizontal text position using one of the
five constants: LEADING, LEFT, CENTER, RIGHT, TRAILING.
• The default horizontal text position is
SwingConstants.RIGHT.

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

• JCheckBox inherits all the properties such as text, icon,


mnemonic, verticalAlignment, horizontalAlignment,
horizontalTextPosition, verticalTextPosition, and selected from
AbstractButton, and provides several constructors to create
check boxes.

javax.swing.AbstractButton

javax.swing.JToggleButton

javax.swing.JCheckBox
+JCheckBox() Creates a default check box button with no text and icon.
+JCheckBox(text: String) Creates a check box with text.
+JCheckBox(text: String, selected: 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

Add three check boxes


named Centered, Bold, and
Italic into the ButtonDemo
example to let the user
specify whether the message
is centered, bold, or italic.

48
JRadioButton

• Radio buttons are variations of check boxes. They


are often used in the group, where only one button
is checked at a time.

javax.swing.AbstractButton

javax.swing.JToggleButton

javax.swing.JRadioButton
+JRadioButton() Creates a default radio button with no text and icon.
+JRadioButton(text: String) Creates a radio button with text.
+JRadioButton(text: String, selected: 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

ButtonGroup btg = new ButtonGroup();


btg.add(jrb1);
btg.add(jrb2);

50
Example: 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.

51
JLabel

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

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

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.

54
Using Labels

// Create an image icon from image file


ImageIcon icon = new ImageIcon("image/grapes.gif");

// Create a label with text, an icon,


// with centered horizontal alignment
JLabel jlbl = new JLabel("Grapes", icon, SwingConstants.CENTER);

// Set label's text alignment and gap between text and icon
jlbl.setHorizontalTextPosition(SwingConstants.CENTER);
jlbl.setVerticalTextPosition(SwingConstants.BOTTOM);
jlbl.setIconTextGap(5);

55
JTextField

A text field is an input area where the user can type in


characters. Text fields are useful in that they enable the user to
enter in variable data (such as a name or a description).

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

Add a text field to the


preceding example to
let the user set a new
message.

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.

• JTextArea(String s, int rows, int


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

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

To add an item to a JComboBox jcbo, use


jcbo.addItem(Object item)

To get an item from JComboBox jcbo, use


jcbo.getItem()

66
Using the itemStateChanged Handler

When a choice is checked or unchecked,


itemStateChanged() for ItemEvent is
invoked as well as the actionPerformed()
handler for ActionEvent.
public void itemStateChanged(ItemEvent e) {
// Make sure the source is a combo box
if (e.getSource() instanceof JComboBox)
String s = (String)e.getItem();
}

67
Example: 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.

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

Creates an empty list.

• JList(Object[] stringItems)
Creates a new list initialized with items.

70
JList Properties

• selectedIndexd
• selectedIndices
• selectedValue
• selectedValues
• selectionMode
• visibleRowCount

71
Example: 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.

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.

+JScrollBar() Creates a default vertical scroll bar.


+JScrollBar(orientation: int) Creates a scroll bar with the specified orientation.
+JScrollBar(orientation: int, value: Creates a scrollbar with the specified orientation, value, extent,
int, extent: int, min: int, max: int) minimum, and maximum.

73
Scroll Bar Properties

Minimal value Maximal value

Block decrement Block increment

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

Rewrite the preceding


program using the sliders
to control a message
displayed on a panel
instead of using scroll
bars.

77
References
• Big Java Late Objects (Horstmann, 2012)
• An Introduction to Problem Solving and Programming
(Savitch, 2012)
• Introduction to Java Programming(Liang, 2011)

Dr. JAMAL-DEEN ADBULAI, CSCD Slide 78

You might also like