User interaction
Lesson Plan
·
Interfaces
o
Buttons
o
Text
fields
o
Text
areas
o
Radio
buttons
o
Checkboxes
o
Combo
boxes
Interfaces
Interface
definition contains a collection of constants and method declarations. A class
that chooses to use (implement) a specific interface should provide
implementation to every interface method. Objects of different classes, which
implement the same interface, can be declared to be of the same, 'interface'
type. This makes it possible to implement polymorphism without an inheritance.
The following example shows how different methods can be executed, using an
interface:
class
Square implements Geom {
int side=1;
public double getArea(){ return side*side;
}
}
class
Circle implements Geom {
int r=1;
public double getArea(){ return
Math.PI*r*r; }
}
class
startAp {
public static void main(String[] args){
Geom g;
g = new Circle();
System.out.println(g.getArea());
g = new Square();
System.out.println(g.getArea());
}
}
interface
Geom {
public double getArea();
}
A common
use of interfaces is to make them containers for constants shared among various
classes. Every class, which implements an interface, gains an automatic access
to these constants. The main use for
interfaces though, is to provide interaction with GUI-based programs.
Event handling model elements:
Event
handling procedure:
Classes,
which support event handling, are provided with java.awt.event package. There are several ways of
grouping events into different categories. Two most general are semantic events
and low-level events. Semantic events are related to user actions on GUI components
(buttons etc.) while low-level events emphasize how events originate. Semantic
events are e.g. action events, item events and others, while low-level events
are mouse events, key events or window events.
Action events -
buttons
When user
clicks a mouse over a button, action events get generated. A button - a
source of an event - should be assigned a listener - an object, which is to be
notified when events occur and which should contain an appropriate
event-handling code. A listener receives a notification along with an Event object through the ActionListener interface.
To assign a
listener to a button use JButton’s method:
·
addActionListener(listener_object)
A listener
should implement ActionListener interface and should specify a code for
processing an event inside an
public void
actionPerformed(ActionEvent e){...} method (which is a method defined in the
interface).
Exercise 1
Write a code, which creates a frame
and adds to that frame a button ("South") and a panel
("Center"). Each time user clicks a button, a new, randomly
selected panel background color should be set.
Use setBackground() method of JPanel object.
Several event listeners can listen to a single event source.
Exercise 2
Write a program which creates a frame and, in addition to two previously
mentioned elements (panel and a button) adds another panel
("North"). Each time the user clicks a button, central panel's
background color should randomly change, and at the same time, a string which
informs what color is currently selected should be displayed (use drawstring(…) method with a color
argument).
The same event listener can process multiple
events.
Exercise 3
Write a program, which displays a panel ("Center") and three
buttons in a row next to each other ("South"). Label
buttons: "Change color", "Deactivate the middle
button" and "Activate the middle button",
respectively. Panel background color should change each time the
user clicks the middle button unless this button is inactive. Use
the getSource() method of the ActionEvent object (which is passed as an
argument of the actionPerformed(.) method) to identify
event source.
A text
field is a basic text control that lets the user enter a small amount of text. JTextField
object constructor can be empty, take an int (which denotes a number of field
columns), a String (which is initially displayed in a field) or both String and int as its arguments. Text fields
fires Action events upon
hitting Return key. To retrieve a text from a text field one can use the
method: getText(), which returns the String object.
Exercise 4
Write a program which creates a label and a text field. Each time the
user hits Enter key, a label should be assigned with the contents of a text
field. Labels are instantiations of the Jlabel class. Use Jlabel's setText(...) method, which takes a String as
an argument to display a text.
Exercise 5
Write a program, which contains a text field and a panel. Each time user hits the "Enter"
key an oval of user-specified diameter should be drawn in a panel
JTextArea is a component that displays multi-line plain
text. Text area lines can be wrapped:
public void setLineWrap(boolean
wrap)
if the argument wrap is set to true. To set line
wrapping at word boundaries, the following method should be executed with a
parameter 'true':
public void setWrapStyleWord(boolean
word)
Some useful methods provided by JTextArea and its superclasses
are:
·
public String getSelectedText()
returns the selected text contained in this
text area (text component). If the selection is null or the document empty,
returns null.
·
public void copy()
transfers the currently selected range in the
associated text model to the system clipboard, leaving the contents in
the text model. The current selection remains intact. Does nothing for null
selections.
·
public void paste()
transfers the contents of the system clipboard
into the associated text model. If there is a selection in the associated view,
it is replaced with the contents of the clipboard. If there is no selection,
the clipboard contents are inserted in front of the current insert position in the
associated view. If the clipboard is empty, does nothing.
·
public void cut()
transfers the currently selected range in the
associated text model to the system clipboard, removing the contents from
the model. The current selection is reset. Does nothing for null selections.
void replaceRange(String str,
int start, int end)
replaces text from the indicated start to end
position with the new text specified.
As in the case of text fields, you can retrieve a text
from a text area using the getText() method, and set the text
using the setText(...) method.
Iinstead of adding text areas (and any other components) directly to a
container, one can add it through a JScrollPane.
JScrollPane provides a panel scrolling capability. To make a component with scroll
bars, one need to make a component to be scrolled to be JScrollPane's constructor
argument, and finally, add the object to a target panel.
Exercise 6
Create a GUI, which contains a scrollable text area and a text field. Text
field text should be automatically transferred to text area (appended) each
time user hits 'Return' key.
A menu bar
contains one or more menus and has a customary, platform-dependent location -
usually along the top of a window. To set the menu bar for a JFrame, you use the setJMenuBar(...) method, which takes a JMenuBar object as its argument.. To
add a JMenu to a JMenuBar, you use the add(JMenu jm) method. To add menu items and
submenus to a JMenu, you use the add(JMenuItem)
method. To detect when the
user selects a JMenuItem, you can listen for action events (just as you would do for a JButton).
Example:
JMenuBar
mb = new JMenuBar();
setJMenuBar(mb);
JMenu me = new JMenu("Edit");
JMenuItem jmi = new JMenuItem("find_x");
me.add(jmi);
mb.add(me);
Exercise 7
Create a GUI which displays a menu of a structure: Edit - Copy, Cut,
Paste, separator, Find; Help - About - Me, MyProgram.
Exercise 8
Add a text area to you GUI and implment simple text editing capabilities:
copying, cutting and pasting
Radio Buttons and radio button groups
Radio buttons are instances of JRadioButton class. Radio buttons can be (should be) combined into
groups. To create a group use the following expression:
ButtonGroup
bg = new ButtonGroup()
To add a
button to a group, use ButtonGroup 's add(...) method,
which takes a name of a radio button object as a parameter. Radio buttons generate events of type ActionEvent.
Exercise 9
Write a program, which displays three radio buttons and a panel.
Selecting a button should set panel's background to red, green and blu,
respectively.
Exercise 10
Write a program which displays three radio buttons, labeled
respectively: "Earth", "Mars" and "Venus" and a
panel. A picture of currently selected planet should be displayed on that
panel.
Check
boxes
Check boxes
are implemented in Java javax.swing package using JCheckBox class. Most common constructors for JCheckBox objects are:
JCheckBox(String some_text_to_appear_next_to_a_box)
JCheckBox(String some_text_to_appear_next_to_a_box, boolean box_initial_status)
JCheckBox objects generate ActionEvents when clicked upon, just like buttons (so ActionListener interface need to be implemented
and actionPerformed(...) method should be overridden to handle events).
To
determine the state of a box (checked or not) use isSelected() method of JCHeckBox - type objects, which returns
Boolean.
Exercise 11
Write a program which contains a check box labeled "Large
Font" and which prints some text (e.g. "This is some text") in
bold using a font "Courier" of size either 24 (if the box is checked)
or 12 (if not checked).
Exercise 12
Add two more check boxes: the former one
labeled "Bold", the latter "Italic". Set text font
according to selected properties.