Java Lecture 6
[Previous Lecture]
[Lecture Index]
[Next Lecture]
Frequently used Listeners/Events
ActionListener:
-
actionPerformed(ActionEvent)
generated by components when they are `activated'
(e.g., Button, MenuItem, List,
TextField, etc.)
ItemListener:
-
itemStateChanged(ItemEvent)
generated by components that allow items to be selected
(e.g., Choice, Checkbox, List, etc.)
MouseListener:
-
mouseEnter(MouseEvent): entered component area
-
mouseExit(MouseEvent): exited component area
-
mouseClick(MouseEvent): button click
-
mousePress(MouseEvent): button press (preceeds drag)
-
mouseRelease(MouseEvent): button release (follows drag)
MouseMotionListener:
-
mouseMove(MouseEvent): no buttons down
-
mouseDrag(MouseEvent): 1 or more buttons down
KeyListener:
-
keyTyped(KeyEvent): normal key event
-
keyPressed(KeyEvent): key held down
-
keyReleased(KeyEvent): held key released
TextFieldDemo.java
/*
* <applet code=TextFieldDemo width=200 height=200>
* </applet>
*/
import java.awt.*;
import java.awt.event.*;
public class TextFieldDemo
extends java.applet.Applet
implements ActionListener
{
TextField t;
public void init() {
t = new TextField();
t.addActionListener(this);
t.setText("Maybe");
add(new Label("Answer: "));
add(t);
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == t) {
System.out.println("Answer is: " + t.getText());
System.out.println("same as: " + e.getActionCommand());
}
return;
}
}
ChoiceDemo.java
/*
* <applet code=ChoiceDemo width=200 height=200>
* </applet>
*/
import java.awt.*;
import java.awt.event.*;
public class ChoiceDemo
extends java.applet.Applet
implements ItemListener
{
Choice c;
public void init() {
c = new Choice();
c.addItemListener(this);
c.add("Yes");
c.add("No");
c.add("Maybe");
add(new Label("Answer: "));
add(c);
}
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == c) {
System.out.println("Answer is: " + c.getSelectedItem());
System.out.println("same as: " + e.getItem());
}
return;
}
}
CheckboxDemo.java
/*
* <applet code=CheckboxDemo width=200 height=200>
* </applet>
*/
import java.awt.*;
import java.awt.event.*;
public class CheckboxDemo
extends java.applet.Applet
implements ItemListener
{
Checkbox c1, c2;
Checkbox cg1, cg2, cg3, cg4;
CheckboxGroup myGroup;
public void init() {
c1 = new Checkbox("Box 1");
c1.addItemListener(this);
c2 = new Checkbox("Box 2", null, true);
c2.addItemListener(new ItemListener() {
public void itemStateChanged( ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED)
System.out.println("Box 2 selected");
}
});
add(c1);
add(c2);
myGroup = new CheckboxGroup();
cg1 = new Checkbox("Option 1");
cg1.setCheckboxGroup(myGroup);
cg1.addItemListener(this);
cg2 = new Checkbox("Option 2", myGroup, false);
cg2.addItemListener(this);
cg3 = new Checkbox("Option 3", myGroup, true);
cg3.addItemListener(this);
cg4 = new Checkbox("Option 4", myGroup, true);
cg4.addItemListener(this);
Panel p = new Panel();
p.setLayout(new GridLayout(2, 2));
p.add(cg1);
p.add(cg2);
p.add(cg3);
p.add(cg4);
add(p);
}
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == c1) {
if (e.getStateChange() == ItemEvent.SELECTED)
System.out.println("Box one selected");
else
System.out.println("Box one de-selected");
return;
}
if (e.getSource() instanceof Checkbox){
Checkbox target = (Checkbox) e.getSource();
if (target.getCheckboxGroup() == myGroup)
{
// target is always equal to
// myGroup.getSelectedCheckbox()
System.out.println( "Current option: "
+ target.getLabel());
return;
}
}
return;
}
}
FrameDemo.java
import java.awt.*;
import java.awt.event.*;
public class FrameDemo
extends Frame
implements ActionListener
{
public static void main(String args[]) {
FrameDemo f = new FrameDemo();
f.pack(); // layout components
f.show(); // display on screen
}
List l;
public FrameDemo() {
super("The Frame test");
l = new List();
l.addActionListener(this);
l.add("abc");
l.add("defg");
l.add("hijk");
add(new Label("Select one: "));
add(l);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == l) {
System.out.println("Selected string:"
+ ae.getActionCommand());
System.out.println("Selected index:"
+ l.getSelectedIndex());
}
}
}
Overview of Components
Canvas
Common Methods to use:
Useful Methods to override:
-
output event handlers (paint(),
update())
-
all input event handlers (mouseUp(), etc.)
Events generated:
Label
Common Methods to use:
-
Label(String s): creates a label
-
Label(String s, int align): creates a label
-
setText(String s): sets the text of the
label.
-
setAlignment(int align): sets the alignment
(LEFT, CENTER, RIGHT).
Events generated:
Button
Common Methods to use:
-
Button(String s): creates a button
-
setLabel(String s): sets the text of the
label.
-
setEnable(boolean en):
disabling greys out button, prevents clicks.
Events generated
-
ActionEvent when button released
event source is the button instance
action command is the button label
Choice
Common Methods to use:
-
Choice(): creates a Choice
-
addItem(String s): adds another string
to the list of choices (added to the end).
-
select(String s): make s the
currently selected choice (it must be an existing
choice).
-
String getSelectedItem(): returns the
currently selected string.
Events generated:
-
ItemEvent when choice is made (even if
choice doesn't change)
event source is the choice instance
event item is the selected choice name
Checkbox
Common Methods to use:
-
Checkbox(String s): creates a checkbox
-
Checkbox(String s, CheckboxGroup g, boolean state):
creates a checkbox in the specified group
-
setLabel(String s): sets the text of the
label.
-
setState(boolean b): checks or unchecks
the checkbox.
If in a group, other checkboxs are unchecked if
b is true.
-
boolean getState(): returns true if the
checkbox is currently checked.
Events generated:
-
ItemEvent when a box is checked or unchecked.
If box is in a group, only one action is generated and
that is the selection of one of the boxes.
event source is the checkbox instance
List
Common Methods to use:
-
List(int nrows, boolean multi): creates a list
with nrows; if multi is true several items can be
selected at once
-
addItem(String s): adds a string to the
list (at the end).
-
addItem(String s, int i): inserts a string
into the list at the specified index.
-
setMultipleMode(boolean b): set whether
several items can be selected at once.
-
select(int i): selects string at
index i.
-
String[] getSelectedItems(): returns an
array of the currently selected strings.
-
int getSelectedIndex(): return the index
of the currently selected item.
Events generated:
-
ActionEvent when item is double clicked
-
ItemEvent when item is selected/deselected
TextField
Common Methods to use:
-
TextField(String s, int cols): creates
a TextField with the specified initial text and size.
-
setText(String s): sets the text that is
being displayed.
-
String getText(): returns the text that
is currently in the TextArea.
-
setEditable(boolean b): sets whether
the user can change the displayed text.
Events generated:
-
ActionEvent when user hits return
action event's command is the current value of
the text
-
TextEvent when text is changed
TextArea
Common Methods to use:
-
TextArea(String s, int rows, int cols): creates
a TextArea with the specified initial text and size.
-
setText(String s): sets the text that is
being displayed.
-
String getText(): returns the text that
is currently in the TextArea.
-
setEditable(boolean b): sets whether
the user can change the displayed text.
Events generated:
-
TextEvent when text is changed
Overview of Layout Managers
FlowLayout
To create:
-
FlowLayout(): creates a FlowLayout with
CENTER alignment
-
FlowLayout(int align):
creates a FlowLayout with
specified alignment (LEFT, CENTER, RIGHT)
To add a component:
add(Component c): adds the component after
any existing components
Notes:
-
lays things out in a row; when row is full,
starts on the next row
-
each row is justified (compoents of a row are bunched
together)
-
rows are placed starting at the top
(not centered vertically)
-
each component is given its natural size (if there
is room)
BorderLayout
To create:
To add a component:
add(String where, Component c): adds the component
in the specified location (Center, East, South, West, North)
Notes:
-
only one component in a location
-
if a location is empty, the space is given to the
Center.
-
if a Center is empty, there is a empty space
in the middle
-
each component is sized to fit the available space
GridLayout
To create:
-
GridLayout(int nrows, int ncols): create
a grid of the specified size.
To add a component:
add(Component c): adds the component to the
next available slot (fills from left to right, top
to bottom)
Notes:
-
if not enough components are added,
number of columns is decreased
-
number of rows or columns is increased as needed
-
each component is sized to fit the available space
CardLayout
To create:
To add a component:
add(String name, Component c): adds the component
to the card deck, component is given the specified name
Notes:
-
only one component is displayed at a time
-
the next(), previous(), and
show() methods can be used to control
which component is displayed
-
each component is sized to fit the available space
Graphics Class
Some selected methods:
- Color getColor()
- void setColor(Color c)
- Font getFont()
- void setFont(Font f)
- void drawLine(int fromX, int fromY, int toX, int toY)
- void drawRect(int ulx, int uly, int width, int height)
- void drawString(String s, int baselineX, y)
- void drawOval(int ulx, int uly, int width, int height)
- void drawArc(int ulx, int uly, int width, int height, int startAngle, int angleDeg)
- void clearRect(int ulx, int uly, int width, int height)
- void fillRect(int ulx, int uly, int width, int height)
- void fill...(...)
- void drawImage(Image img, int ulx, int uly, ImageObserver ob)
[Previous Lecture]
[Lecture Index]
[Next Lecture]