CHAPTER 6 GUI and Event Handling
CHAPTER 6 GUI and Event Handling
1
Creating GUI Objects
Combo
Radio
Label Text Check Box
Button
field Box
Button
2
Creating GUI Objects
// Create a button with text OK
JButton jbtOK = new JButton("OK");
3
Creating GUI Objects
// Create a check box with text bold
JCheckBox jchkBold = new JCheckBox("Bold");
4
Swing vs. AWT
So why do the GUI component classes have a prefix J? Instead
of JButton, why not name it simply Button? In fact, there is a
class already named Button in the java.awt package.
When Java was introduced, the GUI classes were bundled in a
library known as the Abstract Windows Toolkit (AWT). For every
platform on which Java runs, the AWT components are
automatically mapped to the platform-specific components
through their respective agents, known as peers.
AWT is fine for developing simple graphical user interfaces, but
not for developing comprehensive GUI projects.
Besides, AWT is prone to platform-specific bugs because its
peer-based approach relies heavily on the underlying platform.
5
Swing vs. AWT
With the release of Java 2, the AWT user-interface components were
replaced by a more robust, versatile, and flexible library known as Swing
components.
Swing components are painted directly on canvases using Java code,
except for components that are subclasses of java.awt.Window or
java.awt.Panel, which must be drawn using native GUI on a specific
platform.
Swing components are less dependent on the target platform and use less
of the native GUI resource.
For this reason, Swing components that don’t rely on native GUI are
referred to as lightweight components, and AWT components are referred
to as heavyweight components.
6
GUI Class Hierarchy (Swing)
Dimension Classes in the java.awt
LayoutManager package
Heavyweight
Font 1
FontMetrics
Graphics
Lightweight
7
Container Classes
Dimension Classes in the java.awt
LayoutManager package
Heavyweight
Font 1
FontMetrics
Graphics
8
GUI Helper Classes
Dimension Classes in the java.awt
LayoutManager package
Heavyweight
Font 1
FontMetrics
Graphics
JMenuItem JMenu
JToggleButton JCheckBox
JRadioButton
JComponent JEditorPane
JTextArea
10
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
the mouse points on the component without clicking.
-border: javax.swing.border.Border The border for this component.
11
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”));
12
Test Swing Common Features
Component Properties JComponent Properties
• font
• background
toolTipText
border
• foreground
• preferredSize
• minimumSize
• maximumSize
13
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");
14
Co mpo ne nt De sc riptio n
JLabel An area where uneditable text or icons can be displayed.
JTextField An area in which the user inputs data from the keyboard. The area
can also display information.
JButton An area that triggers an event when clicked.
JCheckBox A GUI component that is either selected or not selected.
JComboBox A drop-down list of items from which the user can make a selection
by clicking an item in the list or possibly by typing into the box.
JList An area where a list of items is displayed from which the user can
make a selection by clicking once on any element in the list.
Double-clicking an element in the list generates an action event.
Multiple elements can be selected.
JPanel A container in which components can be placed.
15
JOptionPane
• Using the JOptionPane class is a simple way to display the result of a
computation to the user or receive an input from the user.
• We use the showMessageDialog class method for output.
• We use the showInputDialog class method for input. This method
returns the input as a String value so we need to perform type
conversion for input of other data types.
JOptionPane.showMessageDialog( null, “I Love Java” );
String xx = JOptionPane.showInputDialog( null, “What
is your name?” );
16
Frames
Frame is a window that is not contained inside another
window.
Frame is the basis to contain other user interface components
in Java GUI applications.
The JFrame class can be used to create windows.
For Swing GUI programs, use JFrame class to create widows.
17
JFrame class
javax.swing.JFrame
+JFrame() Creates a default frame with no title.
+JFrame(title: String) Creates a frame with the specified title.
Specifies the size of the frame.
+setSize(width: int, height: int): void
Specifies the upper-left corner location of the frame.
+setLocation(x: int, y: int): void
Sets true to display the frame.
+setVisible(visible: boolean): void
Specifies the operation when the frame is closed.
+setDefaultCloseOperation(mode: int): void Sets the location of the frame relative to the specified
+setLocationRelativeTo(c: Component): void component. If the component is null, the frame is
centered on the screen.
+pack(): void
Automatically sets the frame size to hold the
components in the frame.
18
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.
JPanel p = new JPanel();
p.add(new JButton("OK"));
19
JPanel Class
Create panels, and set the layout for each
Add components to the panels as needed
Add the panels to the content pane (default Border Layout)
BUTTON
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 generalized in
javax.swing.AbstractButton.
20
AbstractButton
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.AbstractButton
-actionCommand: String The action command of this button.
-text: String The button’s text (i.e., the text label on the button).
-icon: javax.swing.Icon The button’s default icon. This icon is also used as the "pressed" and
"disabled" icon if there is no explicitly set pressed icon.
-pressedIcon: javax.swing.Icon The pressed icon (displayed when the button is pressed).
-rolloverIcon: javax.swing.Icon The rollover icon (displayed when the mouse is over the button).
-mnemonic: int 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.
-horizontalAlignment: int The horizontal alignment of the icon and text (default: CENTER).
-horizontalTextPosition: int The horizontal text position relative to the icon (default: RIGHT).
-verticalAlignment: int The vertical alignment of the icon and text (default: CENTER).
-verticalTextPosition: int The vertical text position relative to the icon (default: CENTER).
-borderPainted: boolean Indicates whether the border of the button is painted. By default, a regular
button’s border is painted, but the borders for a check box and a radio
button is not painted.
-iconTextGap: int The gap between the text and the icon on the button (JDK 1.4).
-selected(): boolean The state of the button. True if the check box or radio button is selected,
false if it's not.
21
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.
22
JButton Properties
• text
• icon
• mnemonic
• horizontalAlignment
• verticalAlignment
• horizontalTextPosition
• verticalTextPosition
• iconTextGap
23
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.
Horizontal Alignments
Horizontal alignment specifies how the icon and text are placed horizontally on a button.
You can set the horizontal alignment using one of the five constants: LEADING, LEFT, CENTER, RIGHT,
TRAILING.
At present, LEADING and LEFT are the same and TRAILING and RIGHT are the same.
Future implementation may distinguish them. The default horizontal alignment is SwingConstants.TRAILING.
24
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.
25
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.
26
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.
27
JRadioButton
Radio buttons are variations of check boxes.
They are often used in the group, where only one button is
checked at a time. ButtonGroup btg = new ButtonGroup();
javax.swing.AbstractButton
btg.add(jrb1);
btg.add(jrb2);
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.
28
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.
29
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.
// Create an image icon from image file
ImageIcon icon = new ImageIcon("image/grapes.gif");
// Set label's text alignment and gap between text and icon
jlbl.setHorizontalTextPosition(SwingConstants.CENTER);
jlbl.setVerticalTextPosition(SwingConstants.BOTTOM);
jlbl.setIconTextGap(5);
30
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.
31
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.
• JTextField Properties: • text
• horizontalAlignment
• editable
• columns
32
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.
33
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.
34
JTextArea Properties
• text
• editable
• columns
• lineWrap
• wrapStyleWord
• rows
• lineCount
• tabSize
35
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.
36
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.
37
JList Constructors
• JList(): Creates an empty list.
• selectedIndexd
JList Properties: • selectedIndices
• selectedValue
• selectedValues
• selectionMode
• visibleRowCount
38
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.
39
JTextArea textArea = new JTextArea();
. . .
JScrollPane scrollText = new JScrollPane(textArea);
. . .
contentPane.add(scrollText);
Minimal value Maximal value
Bubble
Unit decrement Unit increment
40
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)
41
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.
• Three Kinds:
• FlowLayout
• GridLayout
• BorderLayout
42
FlowLayout Example
Write a program that adds three labels and text fields
into the content pane of a frame with a FlowLayout
manager.
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.
43
GridLayout Example
Rewrite the program in the preceding example using a GridLayout manager
instead of a FlowLayout manager to display the labels and text fields.
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).
44
The BorderLayout Manager
The BorderLayout manager divides the container into five areas: East, South,
West, North, and Center. Components are added to a BorderLayout by using
the add method.
add(Component, constraint),
where constraint is
BorderLayout.EAST,
BorderLayout.SOUTH,
BorderLayout.WEST, java.awt.BorderLayout
The get and set methods for these data fields are provided in
the class, but omitted in the UML diagram for brevity.
BorderLayout.NORTH, or -hgap: int The horizontal gap of this layout manager (default: 0).
BorderLayout.CENTER. -vgap: int The vertical gap of this layout manager (default: 0).
45
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);
You can use the following methods to set the component’s background
and foreground colors:
setBackground(Color c) e.g. jbt.setBackground(Color.yellow);
46
Adding Colors
Color.black Color.magenta
Color.blue Color.orange
Color.cyan Color.pink
Color.darkGray Color.red
Color.gray Color.white
Color.green Color.yellow
Color.lightGray
47
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.
48
Event-Driven Programming: Events
• Procedural programming is executed in procedural order.
• In event-driven programming, code is executed upon
activation of events.
• An event can be defined as a type of signal to the program
that something has happened.
49
Event Classes
ActionEvent ContainerEvent
TextEvent WindowEvent
ListSelectionEvent
ChangeEvent
50
Selected User Actions
An event object contains whatever properties are pertinent to the event.
You can identify the source object of the event using the getSource() instance
method in the EventObject class.
The subclasses of EventObject deal with special types of events, such as button
actions, window events, component events, mouse movements, and keystrokes.
Source Event Type
User Action Object Generated
Click a button JButton ActionEvent
Click a check box JCheckBox ItemEvent, ActionEvent
Click a radio button JRadioButton ItemEvent, ActionEvent
Press return on a text field JTextField ActionEvent
Select a new item JComboBox ItemEvent, ActionEvent
Window opened, closed, etc. Window WindowEvent
Mouse pressed, released, etc. Component MouseEvent
Key released, pressed, etc. Component KeyEvent
51
Selected Event Handlers
Event Class Listener Interface Listener Methods (Handlers)
ActionEvent ActionListener actionPerformed(ActionEvent)
ItemEvent ItemListener itemStateChanged(ItemEvent)
MouseEvent MouseListener mousePressed(MouseEvent)
mouseReleased(MouseEvent)
mouseClicked(MouseEvent)
mouseExited(MouseEvent)
mouseEntered(MouseEvent)
MouseMotionListener mouseDragged(MouseEvent)
mouseMoved(MouseEvent)
KeyEvent KeyListener keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTypeed(KeyEvent)
52
MouseEvent
java.awt.event.InputEvent
+getWhen(): long Returns the timestamp when this event occurred.
+isAltDown(): boolean Returns whether or not the Alt modifier is down on this event.
+isControlDown(): boolean Returns whether or not the Control modifier is down on this event.
+isMetaDown(): boolean Returns whether or not the Meta modifier is down on this event
+isShiftDown(): boolean Returns whether or not the Shift modifier is down on this event.
java.awt.event.MouseEvent
+getButton(): int Indicates which mouse button has been clicked.
+getClickCount(): int Returns the number of mouse clicks associated with this event.
+getPoint(): java.awt.Point Returns a Point object containing the x and y coordinates.
+getX(): int Returns the x-coordinate of the mouse point.
+getY(): int Returns the y-coordinate of the mouse point.
java.awt.event.MouseListener
+mousePressed(e: MouseEvent): void Invoked when the mouse button has been pressed on the
source component.
+mouseReleased(e: MouseEvent): void Invoked when the mouse button has been released on the
source component.
+mouseClicked(e: MouseEvent): void Invoked when the mouse button has been clicked (pressed and
released) on the source component.
+mouseEntered(e: MouseEvent): void Invoked when the mouse enters the source component.
+mouseExited(e: MouseEvent): void Invoked when the mouse exits the source component.
java.awt.event.MouseMotionListener
+mouseDragged(e: MouseEvent): void Invoked when a mouse button is moved with a button pressed.
+mouseMoved(e: MouseEvent): void Invoked when a mouse button is moved without a button
pressed.
53
Standard AWT Event Listeners
• ItemListener
• Handles selections in lists,
checkboxes, etc.
• itemStateChanged(ItemEvent
event)
• KeyListener
• Detects keyboard events
• keyPressed(KeyEvent event) --
any key pressed down
• keyReleased(KeyEvent event) --
any key released
• keyTyped(KeyEvent event) --
key for printable char released
54
Swing Example
import java.awt.*;
import javax.swing.*;
public MyTest() {
setTitle(“My First GUI”);
setSize(350, 100);
getContentPane().add(myLabel);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main (String args[]) {
MyTest m = new MyTest();
m.setVisible(true);
} 55
Putting all Together
package swinglab;
import java.awt.*;
import javax.swing.*;
import java.util.*;
56
static final String ADD_OP = "ADDITION";
static final String SUB_OP = "SUBTRACTION";
static final String MUL_OP = "MULTIPLICATION";
static final String DIV_OP = "DIVISION";
public Calc() {
super("My Funky Calculator");
Container cp = getContentPane();
setDefaultCloseOperation(EXIT_ON_CLOSE);
cp.setLayout(new FlowLayout());
cp.setBackground(Color.WHITE);
setSize(XSIZE,YSIZE);
cp.add(entryPanel);
cp.add(answerPanel);
}
public static void main(String[] args){
Calc trial = new Calc();
trial.setVisible(true);
}
59
ActionListener Example
import javax.swing.*; // Create a listener
import java.awt.event.*; ButtonListener listener = new ButtonListener();
61
inner class for ItemListener event handling
private JTextField field;
field = new JTextField( "Watch the font style change", 20 );
private class CheckBoxHandler implements ItemListener {
private int valBold = Font.PLAIN;
private int valItalic = Font.PLAIN;
// respond to checkbox events
public void itemStateChanged( ItemEvent event )
{
// process bold checkbox events
if ( event.getSource() == bold )
if ( event.getStateChange() == ItemEvent.SELECTED )
valBold = Font.BOLD;
else
valBold = Font.PLAIN;
// process italic checkbox events
if ( event.getSource() == italic )
if ( event.getStateChange() == ItemEvent.SELECTED )
valItalic = Font.ITALIC;
else
valItalic = Font.PLAIN;
• imagesComboBox.addItemListener(
// anonymous inner class to handle JComboBox events
new ItemListener() {
64
• // Inner class: KeyboardPanel for receiving key input
static class KeyboardPanel extends JPanel implements KeyListener {
private int x = 100, y = 100;
private char keyChar = 'A'; // Default key
public KeyboardPanel() { addKeyListener(this); }
public void keyReleased(KeyEvent e) { }
READING Assignment:
public void keyTyped(KeyEvent e) { } Drawing Geometric Figures
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) { Drawing Strings
case KeyEvent.VK_DOWN: y += 10; break;
case KeyEvent.VK_UP: y -= 10; break; Drawing Lines
case KeyEvent.VK_LEFT: x -= 10; break;
case KeyEvent.VK_RIGHT: x += 10; break; Drawing Rectangles
}
default: keyChar = e.getKeyChar();
Drawing Ovals
repaint(); } }
/** Draw the character */
Drawing Arcs
protected void paintComponent(Graphics g) { Drawing Polygons
super.paintComponent(g);
g.setFont(new Font("TimesRoman", Font.PLAIN, 24));
g.drawString(String.valueOf(keyChar), x, y);
} }
65
Possible Cases Output
package quiz3; pp2 = new JPanel(); pp2.setLayout(new
GridLayout(4,1));
import java.awt.Container; j1 = new JLabel("First Value"); pp1.add(j1);
import java.awt.GridLayout; t1= new JTextField("V1", 20); pp2.add(t1);
import java.awt.event.ActionEvent; j2 = new JLabel("Second Value"); pp1.add(j2);
import java.awt.event.ActionListener; t2= new JTextField("V2", 20); pp2.add(t2);
import javax.swing.*; j3 = new JLabel("Third Value"); pp1.add(j3);
public class Quiz3 extends JFrame{ t3= new JTextField("out", 20); pp2.add(t3);
private final JLabel j1,j2,j3; b1= new JButton("AAAA"); pp1.add(b1);
private final JTextField t1,t2,t3; b2= new JButton("BBBB"); pp2.add(b2);
private final JButton b1,b2; cp.add(pp1);
JPanel pp1, pp2,pp3; cp.add(pp2);
public Quiz3(){
Container cp = getContentPane(); Handles hn = new Handles();
cp.setLayout(new GridLayout(1,3)); b1.addActionListener(hn);
cp.setBackground(new java.awt.Color(100, 100, 100));
b2.addActionListener(hn);
pp1 = new JPanel(); pp1.setLayout(new
GridLayout(4,1)); }
66
Possible cases output
private class Handles implements ActionListener{ public static void main(String[] args) {
public void actionPerformed(ActionEvent e) { // TODO code application logic here
double a = Double.parseDouble(t1.getText()); Quiz3 qq = new Quiz3();
double b = Double.parseDouble(t2.getText());
qq.setSize(300, 200);
double c;
if(e.getSource()==b1){
qq.setDefaultCloseOperation(EXIT_ON_CLOSE);
c=Math.pow(a, b);
qq.setVisible(true);
String ff=Double.toString(c);
t3.setText(ff); }
} }
if(e.getSource()==b2){
c=a*b+40;
String gg = Double.toString(c);
t3.setText(gg);
} } }
67
• package quiz2;
• public class Quiz2 {
• public static int[ ] computes(int[ ] list) {
int[ ] result = new int[list.length];
for (int i = 0, j = result.length - 1;i < list.length; i++, j--)
result[j] = list[i];
return result;
}
• public static int computed(int m){ Quiz_2
if(m==1) return 1; (5%)
else return m*computed(m-1);
}
• public static void main(String[] args) {
int[ ] list1 = {10, 22, 3, 47, 5, 6};
int [ ] list2= computes(list1);
System.out.println("Result one="+Arrays.toString(list2));
System.out.println("Result two="+computed(list1[5]));
}
} 68