An example of text fields in Java
The following applet reads text from oneTextField
and capitalizes it in another TextField.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class CapitalizeApplet extends Applet {
private TextField input;
private TextField output;
public void init () {
// Construct the TextFields
this.input = new TextField(40);
this.output = new TextField(40);
this.output.setEditable(false);
Button b = new Button("Capitalize");
// add the button to the layout
this.add(input);
this.add(b);
this.add(output);
// specify that action events sent by the
// button or the input TextField should be handled
// by the same CapitalizerAction object
CapitalizerAction ca = new CapitalizerAction(input, output);
b.addActionListener(ca);
this.input.addActionListener(ca);
// notice that ActionEvents produced by output are ignored.
}
}
class CapitalizerAction implements ActionListener {
private TextField in;
private TextField out;
public CapitalizerAction(TextField in, TextField out) {
this.in = in;
this.out = out;
}
public void actionPerformed(ActionEvent ae) {
String s = in.getText();
out.setText(s.toUpperCase());
}
}
In this program, a different pattern is used for handling events. The
constructor for the CapitalizerAction
class is used to pass in references to the different components the actionPerformed() method affects. An example of text fields in Java
An alternate pattern uses an inner class so the private fields can be accessed directly.import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class CapitalizeApplet extends Applet {
private TextField input;
private TextField output;
public void init () {
// Construct the TextFields
this.input = new TextField(40);
this.output = new TextField(40);
this.output.setEditable(false);
Button b = new Button("Capitalize");
// add the button to the layout
this.add(input);
this.add(b);
this.add(output);
// specify that action events sent by the
// button or the input TextField should be handled
// by the same CapitalizerAction object
CapitalizerAction ca = new CapitalizerAction();
b.addActionListener(ca);
this.input.addActionListener(ca);
// notice that ActionEvents produced by output are ignored.
}
class CapitalizerAction implements ActionListener {
public void actionPerformed(ActionEvent ae) {
String s = input.getText();
output.setText(s.toUpperCase());
}
}
}
TextArea
Thejava.awt.TextArea
class is a subclass of java.awt.TextComponent
that provides a widget for editing multiple lines of text. It's useful for
input and output.
There are five constructors:
public TextArea()
public TextArea(String text)
public TextArea(int rows, int columns)
public TextArea(String text, int rows, int columns)
public TextArea(String text, int rows, int columns, int scrollbars)
Because of the way Java lays out components, you should not use the noargs
constructor. Either start off with a String
or specify the number of rows and columns this area is expected to hold. For
example, TextArea address = new TextArea("Type your address here", 5, 80);
By default, TextAreas don't have scrollbars. However you can add them by
passing one of these constants to the constructor: TextArea.SCROLLBARS_BOTH
TextArea.SCROLLBARS_HORIZONTAL_ONLY
TextArea.SCROLLBARS_NONE
TextArea.SCROLLBARS_VERTICAL_ONLY
For example, TextArea instructions =
new TextArea("", 15, 70, TextArea.SCROLLBARS_VERTICAL_ONLY);
Unlike text fields, text areas do not generate action events when the user
hits return inside the area. Instead, the line is broken and the caret moves on
to the next row. However, the
getText()
method does return the contents of the TextArea,
and the setText() method
does change it. The setEditable()
method lets you determine whether or not, the user can modify the contents of a
TextField. If these methods
sound familiar it's because they're both inherited from the common superclass
of TextField and TextArea, TextComponent.Furthermore, you can append text to a
TextArea
with the append() method,
insert text into the middle of a TextArea
with the insert() method,
and replace a block of text with the replaceRange()
method:public void insert(String text, int position)
public void append(String text)
public void replaceRange(String text, int start, int end)
TextComponent
BothTextArea and TextField are subclasses of java.awt.TextComponent. This class
contains methods common to both classes including several you've already seen: getText(), setText(), and setEditable().
The TextComponent class also
defines methods for manipulating the selection and the caret and for processing
TextEvents. The selection is used for copy and paste and other purposes. The first character in a
TextComponent
is character 0; the second is character 1, and so on. public int getSelectionStart()
public void setSelectionStart(int selectionStart)
public int getSelectionEnd()
public void setSelectionEnd(int selectionEnd)
public void select(int selectionStart, int selectionEnd)
public void selectAll()
public String getSelectedText()
The caret is the insertion point. It's where text appears when the user
types. There are two methods to adjust it: public void setCaretPosition(int position)
public int getCaretPosition()
TextEvents
BothTextArea and TextField can install a TextListener that catches TextEvents. TextComponents fire TextEvents every time the text of the
component changes. This is more or less every time the user hits a key in the
component. The
java.awt.event.TextListener
interface defines a single method, textValueChanged():public void textValueChanged(TextEvent te)
You register a TextListener
with a TextComponent by
calling the component's addTextListener()
method. For example, TextArea password = new TextArea(24)
password.addTextListener(new PasswordChecker());
However, most of the time it's sufficient to just get and set the text as
you need it. It's really quite rare that you need to process it character by
character. A
TextListener can be
removed by calling removeTextListener().public void
removeTextListener(TextListener tl)java.awt.Canvas
Thejava.awt.Canvas class
is a rectangular area on which you can draw using the methods of java.awt.Graphics discussed last week.
The Canvas class has only
three methods: public Canvas()
public void addNotify()
public void paint(Graphics g)
You generally won't instantiate a canvas directly. Instead you'll subclass
it and override the paint()
method in your subclass to draw the picture you want. For example the following
Canvas
draws a big red oval you can add to your applet.import java.awt.*;
public class RedOval extends Canvas {
public void paint(Graphics g) {
Dimension d = this.getSize();
g.setColor(Color.red);
g.fillOval(0, 0, d.width, d.height);
}
public Dimension getMinimumSize() {
return new Dimension(50, 100);
}
public Dimension getPreferredSize() {
return new Dimension(150, 300);
}
public Dimension getMaximumSize() {
return new Dimension(200, 400);
}
}
Any applet that uses components should not also override paint(). Doing so will have unexpected
effects because of the way Java arranges components. Instead, create a Canvas object and do your drawing in its
paint() method.Custom canvases are added to applets just like any other component. For example,
public void init() {
this.add(new RedOval());
}
Canvases themselves do not normally fire any events. Next week, we'll see
how to change that in the subclasses. An alternate approach
import java.awt.*;
public class ColoredOval extends Canvas {
public ColoredOval() {
this(Color.RED, 100, 100);
}
public ColoredOval(Color c) {
this(c, 100, 100);
}
public ColoredOval(int width, int height) {
this(Color.RED, width, height);
}
public ColoredOval(Color c, int width, int height) {
this.setColor(c);
this.setSize(width, height);
}
public void paint(Graphics g) {
Dimension d = this.getSize();
g.fillOval(0, 0, d.width, d.height);
}
}
This is almost but not quite the same effect as the previous applet. (It's a
little less resizeable.) java.awt.Choice
Thejava.awt.Choice class
implements a popup menu with a fixed position. (The java.awt.PopupMenu class is a popup menu
with no fixed position. It pops up when the user clicks
and holds the right mouse button.)

Creating a choice menu is a little more complex than creating the other user interface components you've seen. There's an extra step, adding the menu items to the menu. That is the five steps are
- Declare the
Choice - Allocate the
Choice - Add the menu items to the
Choice - Add the
Choiceto thelayout - Add an
ItemListenerto theChoice
public void init() {
Choice ch;
ch = new Choice();
ch.addItem("1");
ch.addItem("2");
ch.addItem("3");
ch.addItem("4");
ch.addItem("5");
add(ch);
}
Methods of java.awt.Choice
TheChoice class has a
number of methods to add, remove, and return different items from the list. The
list starts counting at 0. public int getItemCount()
public String getItem(int index)
public void add(String item)
public void addItem(String item)
public void insert(String item, int position)
public void remove(String item)
public void remove(int position)
public void removeAll()
However, most of the item you'll just build the Choice when the applet starts up, and
not modify it later. These methods get or set the current selected item in the
Choice, that is the item that's shown. public void removeAll()
public String getSelectedItem()
public Object[] getSelectedObjects()
public int getSelectedIndex()
public void select(int position)
public void select(String item)
ItemListeners
When the user changes the selected item in aChoice, the Choice
fires two ItemListener
events, one to indicate that the original selection has been deselected and the
other to indicate that a new selection has been made. You can process these
events by registering an ItemListener
object with your Choice. You do not always need to do this. It is not uncommon to only check the value of a
Choice when some
other event occurs like a Button
press.For example, the following applet builds a
Choice menu with the numbers from 1 to 5. When the user
makes a selection, the applet beeps that many times.import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class MultiBeep extends Applet {
public void init() {
Choice ch;
ch = new Choice();
ch.addItem("1");
ch.addItem("2");
ch.addItem("3");
ch.addItem("4");
ch.addItem("5");
this.add(ch);
ch.addItemListener(new BeepItem());
}
}
class BeepItem implements ItemListener {
public void itemStateChanged(ItemEvent ie) {
if (ie.getStateChange() == ItemEvent.SELECTED) {
String name = (String) ie.getItem();
Toolkit tk = Toolkit.getDefaultToolkit();
try {
int n = Integer.parseInt(name);
for (int i = 0; i < n; i++) tk.beep();
}
catch (Exception e) {
tk.beep();
}
}
}
}
The
BeepItem
class implements the ItemListener
interface. It filters out events caused by items being deselected with ItemEvent.getStateChange() and only
beeps if an item was selected. The available convenience constants you can
check are: ItemEvent.DESELECTED
ItemEvent.ITEM_FIRST
ItemEvent.ITEM_LAST
ItemEvent.ITEM_STATE_CHANGED
ItemEvent.SELECTED
The
ItemEvent.getItem()
method is used to retrieve the actual selected item.java.awt.Checkbox
Check boxes are used to select aboolean
value. Each Checkbox has a
label that should be used to tell the user what the Checkbox represents. For instance a Checkbox with the label
"Anchovies" would be checked if the user wants anchovies on their
pizza and unchecked if they don't. 
Checkboxes are often used to select from a list of possible choices when as few selections as zero or as many as everything on the list may be made. Adding a
Checkbox to an applet is
simple. Just declare it, construct it and add it. Checkbox c c = new Checkbox("Pepperoni"));
add(c);
As usual these steps may be combined into the single line add(new
Checkbox("Pepperoni"));By default check boxes are unchecked when created. If you want a
Checkbox to start life checked, use the
following constructor instead:add(new Checkbox("Pepperoni",
null, true));The
null is a reference
to a CheckboxGroup. Passing null for this argument says that this Checkbox does not belong to a CheckboxGroup.Every
Checkbox has a boolean value, either true or false. When the Checkbox
is checked that value is true.
When it is unchecked that value is false. You access this value using the Checkbox's getState() and setState(boolean
b) methods. For example private void handleCheckbox(Checkbox c) {
if (c.getState()) price += 0.50;
else price -= 0.50;
}
Checkbox Events
When the aCheckbox
changes state, normally as a result of user action, it fires an ItemEvent. Most of the time you ignore
this event. Instead you manually check the state of a Checkbox when you need to know it.
However if you want to know immediately when a Checkbox changes state, you can register an ItemListener for the Checkbox. An
ItemEvent is exactly
the same as the item event fired by a Choice.
In fact item events are used to indicate selections or deselections in any sort
of list including checkboxes, radio buttons, choices, and lists.For example, the following program is an applet that asks the age-old question, "What do you want on your pizza?" When an ingredient is checked the price of the pizza goes up by fifty cents. When an ingredient is unchecked fifty cents is taken off. The price is shown in a
TextField.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Ingredients extends Applet {
private TextField display;
private double price = 7.00;
public void init() {
this.add(new Label("What do you want on your pizza?", Label.CENTER));
Pricer p = new Pricer(this);
Checkbox pepperoni = new Checkbox("Pepperoni");
this.add(pepperoni);
pepperoni.addItemListener(p);
Checkbox olives = new Checkbox("Olives");
olives.addItemListener(p);
this.add(olives);
Checkbox onions = new Checkbox("Onions");
onions.addItemListener(p);
this.add(onions);
Checkbox sausage = new Checkbox("Sausage");
sausage.addItemListener(p);
this.add(sausage);
Checkbox peppers = new Checkbox("Peppers");
peppers.addItemListener(p);
this.add(peppers);
Checkbox extraCheese = new Checkbox("Extra Cheese");
extraCheese.addItemListener(p);
this.add(extraCheese);
Checkbox ham = new Checkbox("Ham");
ham.addItemListener(p);
this.add(ham);
Checkbox pineapple = new Checkbox("Pineapple");
pineapple.addItemListener(p);
this.add(pineapplec);
Checkbox anchovies = new Checkbox("Anchovies");
anchovies.addItemListener(p);
this.add(anchovies);
this.display = new TextField(String.valueOf(price));
// so people can't change the price of the pizza
display.setEditable(false);
this.add(display);
}
public void setPrice(double price) {
this.price = price;
display.setText(String.valueOf(price));
}
public double getPrice() {
return this.price;
}
}
class Pricer implements ItemListener {
private Ingredients out;
public Pricer(Ingredients out) {
this.out = out;
}
public void itemStateChanged(ItemEvent ie) {
double price = out.getPrice();
if (ie.getStateChange() == ItemEvent.SELECTED) price += 0.50;
else price -= 0.50;
// Change the price
out.setPrice(price);
}
}
java.awt.CheckboxGroup
Checkbox groups are collections of checkboxes with the special property that no more than one checkbox in the same group can be selected at a time. The checkboxes in aCheckboxGroup
are often called radio buttons. Checkboxes that are members of the same CheckboxGroup cannot be checked
simultaneously. When the user checks one, all others are unchecked
automatically. The constructor for a
CheckboxGroup
is trivial. No arguments are needed. You do not even need to add the CheckboxGroup to the applet since
checkbox groups are themselves not user-interface widgets, just ways of
arranging checkboxes.CheckboxGroup cbg = new
CheckboxGroup();To make check boxes act like radio buttons, use this constructor for each
Checkbox in the group.public Checkbox(String label,
CheckboxGroup cbg, boolean checked)The label is the label for this
Checkbox.
The CheckboxGroup is the
group you want this Checkbox
to belong to and must already exist.At any time, you can get or set the selected
Checkbox with these two methods: public Checkbox getSelectedCheckbox()
public void setSelectedCheckbox(Checkbox box)
java.awt.CheckboxGroup example
The following program asks the customer how they're going to pay for their pizza, Visa, Mastercard, American Express, Discover, cash or check. Someone may want both anchovies and pineapple on their pizza, but they're unlikely to pay with both Visa and American Express.
import java.applet.*;
import java.awt.*;
public class PaymentMethod extends Applet {
public void init() {
this.add(new Label("How will you pay for your pizza?"));
CheckboxGroup cbg = new CheckboxGroup();
this.add(new Checkbox("Visa", cbg, false));
this.add(new Checkbox("Mastercard", cbg, false));
this.add(new Checkbox("American Express", cbg, false));
this.add(new Checkbox("Discover", cbg, false));
this.add(new Checkbox("Cash", cbg, true)); // the default
}
}
There isn't any action in this simple example applet. If you need to add
action as radio buttons are checked and unchecked, you do it just the same as
for any other Checkbox. java.awt.List
Scrolling lists are useful for storing long lists of things one to a line. The things in the list are called items, but each one is just a String. For example,
List Methods
You create a newList
with one of these three constructors: public List()
public List(int numLines)
public List(int numLines, boolean allowMultipleSelections)
For example, List l = new List(8, true);numLines is the number of
items you want to be visible in the scrolling list. It is not necessarily the
same as the number of items in the list which is limited only by available
memory. allowMultipleSelections
says whether the user is allowed to select more than one item at once
(typically by Shift-clicking).The following methods add items at the end of the list:
public void add(String item)
public void addItem(String item)
These two methods add items at the specified position in the list. public void add(String item, int index)
public void addItem(String item, int index)
The following methods remove items from the List: public void removeAll()
public void remove(String item)
public void remove(int position)
public void delItem(int position)
These methods allow you to retrive particular items from the
List: public int getItemCount()
public String getItem(int index)
public String[] getItems()
You ran also replace a particular item: public void replaceItem(String newValue, int index)
These methods allow you to determine which item the user has selected: public int getSelectedIndex()
public int[] getSelectedIndexes()
public String getSelectedItem()
public String[] getSelectedItems()
public Object[] getSelectedObjects()
If a list allows multiple selections, you should use the plural forms of the
above methods. You can determine whether multiple selections are allowed with isMultipleMode() and change it with setMultipleMode(). public boolean isMultipleMode()
public void setMultipleMode(boolean b)
These methods allow you to manipulate the selection: public void select(int index)
public void deselect(int index)
public boolean isIndexSelected(int index)
These two methods determine whether an item at a particular index is
currently visible in the List box: public int getVisibleIndex()
public void makeVisible(int index)
List Events
Lists can fire two separate types of events. When a list item is selected or deselected, theList fires
an ItemEvent. However, when
the user double clicks on a list item, the List
fires an ActionEvent.
Therefore, you can register both an ItemListener
to process selections and/or an ActionListener
to process double clicks. public void addItemListener(ItemListener l)
public void removeItemListener(ItemListener l)
public void addActionListener(ActionListener l)
public void removeActionListener(ActionListener l)
The action command in the ActionEvent
is the list item which was double clicked. java.awt.Scrollbar
Lists, TextAreas, and ScrollPanes come with ready made
scrollbars. However if you want to scroll any other object you'll have to use a
java.awt.Scrollbar.
Scrollbars have many uses. At their most basic they're used for moving the
visible area. They can also be used to set a value between two numbers. Or they
can be used to flip through a number of screens as in a database operation that
looks at successive records. There are three constructors:
public Scrollbar()
public Scrollbar(int orientation)
public Scrollbar(int orientation, int value, int visible, int min, int max)
The orientation argument
is one of the mnemonic constants, Scrollbar.HORIZONTAL
or Scrollbar.VERTICAL. As
you expect this determines whether the Scrollbar
is laid out from left to right or top to bottom. A
Scrollbar has an int value at all times. This value will
be between the minimum and
the maximum value set by the
last two arguments to the constructor. When a Scrollbar is created, its value is given by the value argument. The default is 0.Finally
visible
represents the size of the visible portion of the scrollable area in pixels.
The Scrollbar uses this when
moving up or down a page.A
Scrollbar fires an
adjustment event when its value changes. You register an adjustment listener to
catch this event. This class needs an adjustmentValueChanged()
method with this signature:public void
adjustmentValueChanged(AdjustmentEvent e)The following program is an applet that changes the number in a
TextField between 1 and 100 based on the
position of the thumb (the movable part of the Scrollbar). In a practical application the number would
of course mean something.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Scrollie extends Applet implements AdjustmentListener {
private TextField t;
private Scrollbar sb;
public void init() {
int initialValue = 1;
sb = new Scrollbar(Scrollbar.HORIZONTAL, initialValue, 100, 1, 100);
sb.addAdjustmentListener(this);
this.add(sb);
this.t = new TextField(4);
this.t.setText(String.valueOf(initialValue));
this.add(t);
}
public void adjustmentValueChanged(AdjustmentEvent e)
int val = sb.getValue();
this.t.setText(String.valueOf(val));
}
}
Peer vs. Swing Components
I'm not going to talk much about Swing in this course, but most of what I teach you about the standard AWT components carries over to their Swing equivalents with only trivial changes. For example, here's yet another way to write an applet that says "Cub Scouts!" in 24 point, SansSerif, bold and blue and with a yellow background.import java.awt.*;
import javax.swing.*;
public class SwingCubScout extends JApplet {
public void init() {
JLabel cubScouts = new JLabel("Cub Scouts!");
cubScouts.setForeground(Color.blue);
cubScouts.setBackground(Color.yellow);
cubScouts.setFont(new Font("Sans", Font.BOLD, 24));
this.getContentPane().add(cubScouts);
}
}
This is almost identical to the AWT-based Cub Scout applet, except that I've
imported the javax.swing
package and changed Label to
JLabel and Applet to JApplet. Week 6 Exercises
- Write an applet that with a 60 column by 10 row text area that allows the user to type some text. Add a button to this applet that clears the text area when it's pressed.
Don't worry excessively about making the applet
look good. Before you can do that you'll need to learn about layout managers.
- Rewrite the payroll problem from week 2 as an applet. Provide a text field for the number of hours, a text field for the pay rate, and a non-editable text field for the output. Also provide labels to identify all three text fields and a button to calculate the result.
Don't worry about minimum wage, number of hours in
the week, or other error conditions we checked before. In the event the user
enters data that cannot be interpreted as a number, don't put anything in the
output text field. In a couple of weeks, you'll learn how to bring up an error
dialog to handle these conditions.
Don't worry excessively about making the applet
look good. Before you can do that you'll need to learn about layout managers.
We'll cover them next week
Getting into more fun Graphics
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ShowColors2 extends JFrame {
private JButton changeColorButton;
private Color color = Color.LIGHT_GRAY;
private Container container;
// set up GUI
public ShowColors2()
{
super( "Using JColorChooser" );
container = getContentPane();
container.setLayout( new FlowLayout() );
// set up changeColorButton and register its event handler
changeColorButton = new JButton( "Change Color" );
changeColorButton.addActionListener(
new ActionListener() { // anonymous inner class
// display JColorChooser when user clicks button
public void actionPerformed( ActionEvent event )
{
color = JColorChooser.showDialog(
ShowColors2.this, "Choose a color", color );
// set default color, if no color is returned
if ( color == null )
color = Color.LIGHT_GRAY;
// change content pane's background color
container.setBackground( color );
}
} // end anonymous inner class
); // end call to addActionListener
container.add( changeColorButton );
setSize( 400, 130 );
setVisible( true );
} // end ShowColor2 constructor
// execute application
public static void main( String args[] )
{
ShowColors2 application = new ShowColors2();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class Shapes2 extends JFrame {
// set window's title bar String, background color and dimensions
public Shapes2()
{
super( "Drawing 2D Shapes" );
getContentPane().setBackground( Color.WHITE );
setSize( 400, 400 );
setVisible( true );
}
// draw general paths
public void paint( Graphics g )
{
super.paint( g ); // call superclass's paint method
int xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };
int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };
Graphics2D g2d = ( Graphics2D ) g;
GeneralPath star = new GeneralPath(); // create GeneralPath object
// set the initial coordinate of the General Path
star.moveTo( xPoints[ 0 ], yPoints[ 0 ] );
// create the star--this does not draw the star
for ( int count = 1; count < xPoints.length; count++ )
star.lineTo( xPoints[ count ], yPoints[ count ] );
star.closePath(); // close the shape
g2d.translate( 200, 200 ); // translate the origin to (200, 200)
// rotate around origin and draw stars in random colors
for ( int count = 1; count <= 20; count++ ) {
g2d.rotate( Math.PI / 10.0 ); // rotate coordinate system
// set random drawing color
g2d.setColor( new Color( ( int ) ( Math.random() * 256 ),
( int ) ( Math.random() * 256 ),
( int ) ( Math.random() * 256 ) ) );
g2d.fill( star ); // draw filled star
}
} // end method paint
// execute application
public static void main( String args[] )
{
Shapes2 application = new Shapes2();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
An example of text fields in Java
The following applet reads text from oneTextFieldand capitalizes it in anotherTextField.
![]()
import java.applet.*;import java.awt.*;import java.awt.event.*;public class CapitalizeApplet extends Applet {private TextField input;private TextField output;public void init () {// Construct the TextFieldsthis.input = new TextField(40);this.output = new TextField(40);this.output.setEditable(false);Button b = new Button("Capitalize");// add the button to the layoutthis.add(input);this.add(b);this.add(output);// specify that action events sent by the// button or the input TextField should be handled// by the same CapitalizerAction objectCapitalizerAction ca = new CapitalizerAction(input, output);b.addActionListener(ca);this.input.addActionListener(ca);// notice that ActionEvents produced by output are ignored.}}class CapitalizerAction implements ActionListener {private TextField in;private TextField out;public CapitalizerAction(TextField in, TextField out) {this.in = in;this.out = out;}public void actionPerformed(ActionEvent ae) {String s = in.getText();out.setText(s.toUpperCase());}In this program, a different pattern is used for handling events. The constructor for the}CapitalizerActionclass is used to pass in references to the different components theactionPerformed()method affects.
An example of text fields in Java
An alternate pattern uses an inner class so the private fields can be accessed directly.
import java.applet.*;import java.awt.*;import java.awt.event.*;public class CapitalizeApplet extends Applet {private TextField input;private TextField output;public void init () {// Construct the TextFieldsthis.input = new TextField(40);this.output = new TextField(40);this.output.setEditable(false);Button b = new Button("Capitalize");// add the button to the layoutthis.add(input);this.add(b);this.add(output);// specify that action events sent by the// button or the input TextField should be handled// by the same CapitalizerAction objectCapitalizerAction ca = new CapitalizerAction();b.addActionListener(ca);this.input.addActionListener(ca);// notice that ActionEvents produced by output are ignored.}class CapitalizerAction implements ActionListener {public void actionPerformed(ActionEvent ae) {String s = input.getText();output.setText(s.toUpperCase());}}}TextArea
Thejava.awt.TextAreaclass is a subclass ofjava.awt.TextComponentthat provides a widget for editing multiple lines of text. It's useful for input and output.
There are five constructors:
public TextArea()public TextArea(String text)public TextArea(int rows, int columns)public TextArea(String text, int rows, int columns)Because of the way Java lays out components, you should not use the noargs constructor. Either start off with apublic TextArea(String text, int rows, int columns, int scrollbars)Stringor specify the number of rows and columns this area is expected to hold. For example,
By default, TextAreas don't have scrollbars. However you can add them by passing one of these constants to the constructor:TextArea address = new TextArea("Type your address here", 5, 80);
TextArea.SCROLLBARS_BOTHTextArea.SCROLLBARS_HORIZONTAL_ONLYTextArea.SCROLLBARS_NONEFor example,TextArea.SCROLLBARS_VERTICAL_ONLY
TextArea instructions =Unlike text fields, text areas do not generate action events when the user hits return inside the area. Instead, the line is broken and the caret moves on to the next row.new TextArea("", 15, 70, TextArea.SCROLLBARS_VERTICAL_ONLY);
However, thegetText()method does return the contents of theTextArea, and thesetText()method does change it. ThesetEditable()method lets you determine whether or not, the user can modify the contents of aTextField. If these methods sound familiar it's because they're both inherited from the common superclass ofTextFieldandTextArea,TextComponent.
Furthermore, you can append text to aTextAreawith theappend()method, insert text into the middle of aTextAreawith theinsert()method, and replace a block of text with thereplaceRange()method:
public void insert(String text, int position)public void append(String text)public void replaceRange(String text, int start, int end)TextComponent
BothTextAreaandTextFieldare subclasses ofjava.awt.TextComponent. This class contains methods common to both classes including several you've already seen:getText(),setText(), andsetEditable(). TheTextComponentclass also defines methods for manipulating the selection and the caret and for processingTextEvents.
The selection is used for copy and paste and other purposes. The first character in aTextComponentis character 0; the second is character 1, and so on.
public int getSelectionStart()public void setSelectionStart(int selectionStart)public int getSelectionEnd()public void setSelectionEnd(int selectionEnd)public void select(int selectionStart, int selectionEnd)public void selectAll()The caret is the insertion point. It's where text appears when the user types. There are two methods to adjust it:public String getSelectedText()
public void setCaretPosition(int position)public int getCaretPosition()TextEvents
BothTextAreaandTextFieldcan install aTextListenerthat catchesTextEvents.TextComponents fireTextEvents every time the text of the component changes. This is more or less every time the user hits a key in the component.
Thejava.awt.event.TextListenerinterface defines a single method,textValueChanged():
You register apublic void textValueChanged(TextEvent te)TextListenerwith aTextComponentby calling the component'saddTextListener()method. For example,
TextArea password = new TextArea(24)However, most of the time it's sufficient to just get and set the text as you need it. It's really quite rare that you need to process it character by character.password.addTextListener(new PasswordChecker());
ATextListenercan be removed by callingremoveTextListener().
public void removeTextListener(TextListener tl)
java.awt.Canvas
Thejava.awt.Canvasclass is a rectangular area on which you can draw using the methods ofjava.awt.Graphicsdiscussed last week. TheCanvasclass has only three methods:
public Canvas()public void addNotify()You generally won't instantiate a canvas directly. Instead you'll subclass it and override thepublic void paint(Graphics g)paint()method in your subclass to draw the picture you want.
For example the followingCanvasdraws a big red oval you can add to your applet.
import java.awt.*;public class RedOval extends Canvas {public void paint(Graphics g) {Dimension d = this.getSize();g.setColor(Color.red);g.fillOval(0, 0, d.width, d.height);}public Dimension getMinimumSize() {return new Dimension(50, 100);}public Dimension getPreferredSize() {return new Dimension(150, 300);}public Dimension getMaximumSize() {return new Dimension(200, 400);}Any applet that uses components should not also override}paint(). Doing so will have unexpected effects because of the way Java arranges components. Instead, create aCanvasobject and do your drawing in itspaint()method.
Custom canvases are added to applets just like any other component. For example,
public void init() {this.add(new RedOval());Canvases themselves do not normally fire any events. Next week, we'll see how to change that in the subclasses.}
An alternate approach
import java.awt.*;public class ColoredOval extends Canvas {public ColoredOval() {this(Color.RED, 100, 100);}public ColoredOval(Color c) {this(c, 100, 100);}public ColoredOval(int width, int height) {this(Color.RED, width, height);}public ColoredOval(Color c, int width, int height) {this.setColor(c);this.setSize(width, height);}public void paint(Graphics g) {Dimension d = this.getSize();g.fillOval(0, 0, d.width, d.height);}This is almost but not quite the same effect as the previous applet. (It's a little less resizeable.)}
java.awt.Choice
Thejava.awt.Choiceclass implements a popup menu with a fixed position. (Thejava.awt.PopupMenuclass is a popup menu with no fixed position. It pops up when the user clicks
and holds the right mouse button.)
Creating a choice menu is a little more complex than creating the other user interface components you've seen. There's an extra step, adding the menu items to the menu. That is the five steps are
For example
- Declare the
Choice- Allocate the
Choice- Add the menu items to the
Choice- Add the
Choiceto thelayout- Add an
ItemListenerto theChoice
public void init() {Choice ch;ch = new Choice();ch.addItem("1");ch.addItem("2");ch.addItem("3");ch.addItem("4");ch.addItem("5");add(ch);}Methods of java.awt.Choice
TheChoiceclass has a number of methods to add, remove, and return different items from the list. The list starts counting at 0.
public int getItemCount()public String getItem(int index)public void add(String item)public void addItem(String item)public void insert(String item, int position)public void remove(String item)public void remove(int position)However, most of the item you'll just build thepublic void removeAll()Choicewhen the applet starts up, and not modify it later.
These methods get or set the current selected item in theChoice, that is the item that's shown.
public void removeAll()public String getSelectedItem()public Object[] getSelectedObjects()public int getSelectedIndex()public void select(int position)public void select(String item)ItemListeners
When the user changes the selected item in aChoice, theChoicefires twoItemListenerevents, one to indicate that the original selection has been deselected and the other to indicate that a new selection has been made. You can process these events by registering anItemListenerobject with yourChoice.
You do not always need to do this. It is not uncommon to only check the value of aChoicewhen some other event occurs like aButtonpress.
For example, the following applet builds aChoicemenu with the numbers from 1 to 5. When the user makes a selection, the applet beeps that many times.
import java.applet.*;import java.awt.*;import java.awt.event.*;public class MultiBeep extends Applet {public void init() {Choice ch;ch = new Choice();ch.addItem("1");ch.addItem("2");ch.addItem("3");ch.addItem("4");ch.addItem("5");this.add(ch);ch.addItemListener(new BeepItem());}}class BeepItem implements ItemListener {public void itemStateChanged(ItemEvent ie) {if (ie.getStateChange() == ItemEvent.SELECTED) {String name = (String) ie.getItem();Toolkit tk = Toolkit.getDefaultToolkit();try {int n = Integer.parseInt(name);for (int i = 0; i < n; i++) tk.beep();}catch (Exception e) {tk.beep();}}}}TheBeepItemclass implements theItemListenerinterface. It filters out events caused by items being deselected withItemEvent.getStateChange()and only beeps if an item was selected. The available convenience constants you can check are:ItemEvent.DESELECTEDItemEvent.ITEM_FIRSTItemEvent.ITEM_LASTItemEvent.ITEM_STATE_CHANGEDItemEvent.SELECTEDTheItemEvent.getItem()method is used to retrieve the actual selected item.java.awt.Checkbox
Check boxes are used to select abooleanvalue. EachCheckboxhas a label that should be used to tell the user what theCheckboxrepresents. For instance aCheckboxwith the label "Anchovies" would be checked if the user wants anchovies on their pizza and unchecked if they don't.
Checkboxes are often used to select from a list of possible choices when as few selections as zero or as many as everything on the list may be made. Adding aCheckboxto an applet is simple. Just declare it, construct it and add it.
Checkbox c c = new Checkbox("Pepperoni"));As usual these steps may be combined into the single lineadd(c);
add(new Checkbox("Pepperoni"));
By default check boxes are unchecked when created. If you want aCheckboxto start life checked, use the following constructor instead:
add(new Checkbox("Pepperoni", null, true));
Thenullis a reference to aCheckboxGroup. Passingnullfor this argument says that thisCheckboxdoes not belong to aCheckboxGroup.
EveryCheckboxhas abooleanvalue, eithertrueorfalse. When theCheckboxis checked that value istrue. When it is unchecked that value is false. You access this value using theCheckbox'sgetState()andsetState(boolean b)methods. For example
private void handleCheckbox(Checkbox c) {if (c.getState()) price += 0.50;else price -= 0.50;}Checkbox Events
When the aCheckboxchanges state, normally as a result of user action, it fires anItemEvent. Most of the time you ignore this event. Instead you manually check the state of aCheckboxwhen you need to know it. However if you want to know immediately when aCheckboxchanges state, you can register anItemListenerfor theCheckbox.
AnItemEventis exactly the same as the item event fired by aChoice. In fact item events are used to indicate selections or deselections in any sort of list including checkboxes, radio buttons, choices, and lists.
For example, the following program is an applet that asks the age-old question, "What do you want on your pizza?" When an ingredient is checked the price of the pizza goes up by fifty cents. When an ingredient is unchecked fifty cents is taken off. The price is shown in aTextField.
![]()
import java.applet.*;import java.awt.*;import java.awt.event.*;public class Ingredients extends Applet {private TextField display;private double price = 7.00;public void init() {this.add(new Label("What do you want on your pizza?", Label.CENTER));Pricer p = new Pricer(this);Checkbox pepperoni = new Checkbox("Pepperoni");this.add(pepperoni);pepperoni.addItemListener(p);Checkbox olives = new Checkbox("Olives");olives.addItemListener(p);this.add(olives);Checkbox onions = new Checkbox("Onions");onions.addItemListener(p);this.add(onions);Checkbox sausage = new Checkbox("Sausage");sausage.addItemListener(p);this.add(sausage);Checkbox peppers = new Checkbox("Peppers");peppers.addItemListener(p);this.add(peppers);Checkbox extraCheese = new Checkbox("Extra Cheese");extraCheese.addItemListener(p);this.add(extraCheese);Checkbox ham = new Checkbox("Ham");ham.addItemListener(p);this.add(ham);Checkbox pineapple = new Checkbox("Pineapple");pineapple.addItemListener(p);this.add(pineapplec);Checkbox anchovies = new Checkbox("Anchovies");anchovies.addItemListener(p);this.add(anchovies);this.display = new TextField(String.valueOf(price));// so people can't change the price of the pizzadisplay.setEditable(false);this.add(display);}public void setPrice(double price) {this.price = price;display.setText(String.valueOf(price));}public double getPrice() {return this.price;}}class Pricer implements ItemListener {private Ingredients out;public Pricer(Ingredients out) {this.out = out;}public void itemStateChanged(ItemEvent ie) {double price = out.getPrice();if (ie.getStateChange() == ItemEvent.SELECTED) price += 0.50;else price -= 0.50;// Change the priceout.setPrice(price);}}java.awt.CheckboxGroup
Checkbox groups are collections of checkboxes with the special property that no more than one checkbox in the same group can be selected at a time. The checkboxes in aCheckboxGroupare often called radio buttons. Checkboxes that are members of the sameCheckboxGroupcannot be checked simultaneously. When the user checks one, all others are unchecked automatically.
The constructor for aCheckboxGroupis trivial. No arguments are needed. You do not even need to add theCheckboxGroupto the applet since checkbox groups are themselves not user-interface widgets, just ways of arranging checkboxes.
CheckboxGroup cbg = new CheckboxGroup();
To make check boxes act like radio buttons, use this constructor for eachCheckboxin the group.
public Checkbox(String label, CheckboxGroup cbg, boolean checked)
The label is the label for thisCheckbox. TheCheckboxGroupis the group you want thisCheckboxto belong to and must already exist.
At any time, you can get or set the selectedCheckboxwith these two methods:
public Checkbox getSelectedCheckbox()public void setSelectedCheckbox(Checkbox box)java.awt.CheckboxGroup example
The following program asks the customer how they're going to pay for their pizza, Visa, Mastercard, American Express, Discover, cash or check. Someone may want both anchovies and pineapple on their pizza, but they're unlikely to pay with both Visa and American Express.
![]()
import java.applet.*;import java.awt.*;public class PaymentMethod extends Applet {public void init() {this.add(new Label("How will you pay for your pizza?"));CheckboxGroup cbg = new CheckboxGroup();this.add(new Checkbox("Visa", cbg, false));this.add(new Checkbox("Mastercard", cbg, false));this.add(new Checkbox("American Express", cbg, false));this.add(new Checkbox("Discover", cbg, false));this.add(new Checkbox("Cash", cbg, true)); // the default}There isn't any action in this simple example applet. If you need to add action as radio buttons are checked and unchecked, you do it just the same as for any other}Checkbox.
java.awt.List
Scrolling lists are useful for storing long lists of things one to a line. The things in the list are called items, but each one is just a String. For example,
List Methods
You create a newListwith one of these three constructors:
public List()public List(int numLines)For example,public List(int numLines, boolean allowMultipleSelections)
List l = new List(8, true);
numLinesis the number of items you want to be visible in the scrolling list. It is not necessarily the same as the number of items in the list which is limited only by available memory.allowMultipleSelectionssays whether the user is allowed to select more than one item at once (typically by Shift-clicking).
The following methods add items at the end of the list:
public void add(String item)These two methods add items at the specified position in the list.public void addItem(String item)
public void add(String item, int index)The following methods remove items from thepublic void addItem(String item, int index)List:
public void removeAll()public void remove(String item)public void remove(int position)public void delItem(int position)These methods allow you to retrive particular items from theList:public int getItemCount()public String getItem(int index)You ran also replace a particular item:public String[] getItems()
These methods allow you to determine which item the user has selected:public void replaceItem(String newValue, int index)
public int getSelectedIndex()public int[] getSelectedIndexes()public String getSelectedItem()public String[] getSelectedItems()If a list allows multiple selections, you should use the plural forms of the above methods. You can determine whether multiple selections are allowed withpublic Object[] getSelectedObjects()isMultipleMode()and change it withsetMultipleMode().
public boolean isMultipleMode()These methods allow you to manipulate the selection:public void setMultipleMode(boolean b)
public void select(int index)public void deselect(int index)These two methods determine whether an item at a particular index is currently visible in the List box:public boolean isIndexSelected(int index)
public int getVisibleIndex()public void makeVisible(int index)List Events
Lists can fire two separate types of events. When a list item is selected or deselected, theListfires anItemEvent. However, when the user double clicks on a list item, theListfires anActionEvent. Therefore, you can register both anItemListenerto process selections and/or anActionListenerto process double clicks.
public void addItemListener(ItemListener l)public void removeItemListener(ItemListener l)public void addActionListener(ActionListener l)The action command in thepublic void removeActionListener(ActionListener l)ActionEventis the list item which was double clicked.
java.awt.Scrollbar
Lists,TextAreas, andScrollPanes come with ready made scrollbars. However if you want to scroll any other object you'll have to use ajava.awt.Scrollbar. Scrollbars have many uses. At their most basic they're used for moving the visible area. They can also be used to set a value between two numbers. Or they can be used to flip through a number of screens as in a database operation that looks at successive records.
There are three constructors:
public Scrollbar()public Scrollbar(int orientation)Thepublic Scrollbar(int orientation, int value, int visible, int min, int max)orientationargument is one of the mnemonic constants,Scrollbar.HORIZONTALorScrollbar.VERTICAL. As you expect this determines whether theScrollbaris laid out from left to right or top to bottom.
AScrollbarhas anintvalue at all times. This value will be between theminimumand themaximumvalue set by the last two arguments to the constructor. When aScrollbaris created, its value is given by thevalueargument. The default is 0.
Finallyvisiblerepresents the size of the visible portion of the scrollable area in pixels. TheScrollbaruses this when moving up or down a page.
AScrollbarfires an adjustment event when its value changes. You register an adjustment listener to catch this event. This class needs anadjustmentValueChanged()method with this signature:
public void adjustmentValueChanged(AdjustmentEvent e)
The following program is an applet that changes the number in aTextFieldbetween 1 and 100 based on the position of the thumb (the movable part of theScrollbar). In a practical application the number would of course mean something.
import java.applet.*;import java.awt.*;import java.awt.event.*;public class Scrollie extends Applet implements AdjustmentListener {private TextField t;private Scrollbar sb;public void init() {int initialValue = 1;sb = new Scrollbar(Scrollbar.HORIZONTAL, initialValue, 100, 1, 100);sb.addAdjustmentListener(this);this.add(sb);this.t = new TextField(4);this.t.setText(String.valueOf(initialValue));this.add(t);}public void adjustmentValueChanged(AdjustmentEvent e)int val = sb.getValue();this.t.setText(String.valueOf(val));}}Peer vs. Swing Components
I'm not going to talk much about Swing in this course, but most of what I teach you about the standard AWT components carries over to their Swing equivalents with only trivial changes. For example, here's yet another way to write an applet that says "Cub Scouts!" in 24 point, SansSerif, bold and blue and with a yellow background.
import java.awt.*;import javax.swing.*;public class SwingCubScout extends JApplet {public void init() {JLabel cubScouts = new JLabel("Cub Scouts!");cubScouts.setForeground(Color.blue);cubScouts.setBackground(Color.yellow);cubScouts.setFont(new Font("Sans", Font.BOLD, 24));this.getContentPane().add(cubScouts);}This is almost identical to the AWT-based Cub Scout applet, except that I've imported the}javax.swingpackage and changedLabeltoJLabelandApplettoJApplet.
Week 6 Exercises
- Write an applet that with a 60 column by 10 row text area that allows the user to type some text. Add a button to this applet that clears the text area when it's pressed.
Don't worry excessively about making the applet look good. Before you can do that you'll need to learn about layout managers.
- Rewrite the payroll problem from week 2 as an applet. Provide a text field for the number of hours, a text field for the pay rate, and a non-editable text field for the output. Also provide labels to identify all three text fields and a button to calculate the result.
Don't worry about minimum wage, number of hours in the week, or other error conditions we checked before. In the event the user enters data that cannot be interpreted as a number, don't put anything in the output text field. In a couple of weeks, you'll learn how to bring up an error dialog to handle these conditions.Don't worry excessively about making the applet look good. Before you can do that you'll need to learn about layout managers. We'll cover them next weekGetting into more fun Graphicsimport java.awt.*;import java.awt.event.*;import javax.swing.*;public class ShowColors2 extends JFrame {private JButton changeColorButton;private Color color = Color.LIGHT_GRAY;private Container container;// set up GUIpublic ShowColors2(){super( "Using JColorChooser" );container = getContentPane();container.setLayout( new FlowLayout() );// set up changeColorButton and register its event handlerchangeColorButton = new JButton( "Change Color" );changeColorButton.addActionListener(new ActionListener() { // anonymous inner class// display JColorChooser when user clicks buttonpublic void actionPerformed( ActionEvent event ){color = JColorChooser.showDialog(ShowColors2.this, "Choose a color", color );// set default color, if no color is returnedif ( color == null )color = Color.LIGHT_GRAY;// change content pane's background colorcontainer.setBackground( color );}} // end anonymous inner class); // end call to addActionListenercontainer.add( changeColorButton );setSize( 400, 130 );setVisible( true );} // end ShowColor2 constructor// execute applicationpublic static void main( String args[] ){ShowColors2 application = new ShowColors2();application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );}}import java.awt.*;import java.awt.geom.*;import javax.swing.*;public class Shapes2 extends JFrame {// set window's title bar String, background color and dimensionspublic Shapes2(){super( "Drawing 2D Shapes" );getContentPane().setBackground( Color.WHITE );setSize( 400, 400 );setVisible( true );}// draw general pathspublic void paint( Graphics g ){super.paint( g ); // call superclass's paint methodint xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };Graphics2D g2d = ( Graphics2D ) g;GeneralPath star = new GeneralPath(); // create GeneralPath object// set the initial coordinate of the General Pathstar.moveTo( xPoints[ 0 ], yPoints[ 0 ] );// create the star--this does not draw the starfor ( int count = 1; count < xPoints.length; count++ )star.lineTo( xPoints[ count ], yPoints[ count ] );star.closePath(); // close the shapeg2d.translate( 200, 200 ); // translate the origin to (200, 200)// rotate around origin and draw stars in random colorsfor ( int count = 1; count <= 20; count++ ) {g2d.rotate( Math.PI / 10.0 ); // rotate coordinate system// set random drawing colorg2d.setColor( new Color( ( int ) ( Math.random() * 256 ),( int ) ( Math.random() * 256 ),( int ) ( Math.random() * 256 ) ) );g2d.fill( star ); // draw filled star}} // end method paint// execute applicationpublic static void main( String args[] ){Shapes2 application = new Shapes2();application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );}}
An example of text fields in Java
The following applet reads text from oneTextFieldand capitalizes it in anotherTextField.
![]()
import java.applet.*;import java.awt.*;import java.awt.event.*;public class CapitalizeApplet extends Applet {private TextField input;private TextField output;public void init () {// Construct the TextFieldsthis.input = new TextField(40);this.output = new TextField(40);this.output.setEditable(false);Button b = new Button("Capitalize");// add the button to the layoutthis.add(input);this.add(b);this.add(output);// specify that action events sent by the// button or the input TextField should be handled// by the same CapitalizerAction objectCapitalizerAction ca = new CapitalizerAction(input, output);b.addActionListener(ca);this.input.addActionListener(ca);// notice that ActionEvents produced by output are ignored.}}class CapitalizerAction implements ActionListener {private TextField in;private TextField out;public CapitalizerAction(TextField in, TextField out) {this.in = in;this.out = out;}public void actionPerformed(ActionEvent ae) {String s = in.getText();out.setText(s.toUpperCase());}In this program, a different pattern is used for handling events. The constructor for the}CapitalizerActionclass is used to pass in references to the different components theactionPerformed()method affects.
An example of text fields in Java
An alternate pattern uses an inner class so the private fields can be accessed directly.
import java.applet.*;import java.awt.*;import java.awt.event.*;public class CapitalizeApplet extends Applet {private TextField input;private TextField output;public void init () {// Construct the TextFieldsthis.input = new TextField(40);this.output = new TextField(40);this.output.setEditable(false);Button b = new Button("Capitalize");// add the button to the layoutthis.add(input);this.add(b);this.add(output);// specify that action events sent by the// button or the input TextField should be handled// by the same CapitalizerAction objectCapitalizerAction ca = new CapitalizerAction();b.addActionListener(ca);this.input.addActionListener(ca);// notice that ActionEvents produced by output are ignored.}class CapitalizerAction implements ActionListener {public void actionPerformed(ActionEvent ae) {String s = input.getText();output.setText(s.toUpperCase());}}}TextArea
Thejava.awt.TextAreaclass is a subclass ofjava.awt.TextComponentthat provides a widget for editing multiple lines of text. It's useful for input and output.
There are five constructors:
public TextArea()public TextArea(String text)public TextArea(int rows, int columns)public TextArea(String text, int rows, int columns)Because of the way Java lays out components, you should not use the noargs constructor. Either start off with apublic TextArea(String text, int rows, int columns, int scrollbars)Stringor specify the number of rows and columns this area is expected to hold. For example,
By default, TextAreas don't have scrollbars. However you can add them by passing one of these constants to the constructor:TextArea address = new TextArea("Type your address here", 5, 80);
TextArea.SCROLLBARS_BOTHTextArea.SCROLLBARS_HORIZONTAL_ONLYTextArea.SCROLLBARS_NONEFor example,TextArea.SCROLLBARS_VERTICAL_ONLY
TextArea instructions =Unlike text fields, text areas do not generate action events when the user hits return inside the area. Instead, the line is broken and the caret moves on to the next row.new TextArea("", 15, 70, TextArea.SCROLLBARS_VERTICAL_ONLY);
However, thegetText()method does return the contents of theTextArea, and thesetText()method does change it. ThesetEditable()method lets you determine whether or not, the user can modify the contents of aTextField. If these methods sound familiar it's because they're both inherited from the common superclass ofTextFieldandTextArea,TextComponent.
Furthermore, you can append text to aTextAreawith theappend()method, insert text into the middle of aTextAreawith theinsert()method, and replace a block of text with thereplaceRange()method:
public void insert(String text, int position)public void append(String text)public void replaceRange(String text, int start, int end)TextComponent
BothTextAreaandTextFieldare subclasses ofjava.awt.TextComponent. This class contains methods common to both classes including several you've already seen:getText(),setText(), andsetEditable(). TheTextComponentclass also defines methods for manipulating the selection and the caret and for processingTextEvents.
The selection is used for copy and paste and other purposes. The first character in aTextComponentis character 0; the second is character 1, and so on.
public int getSelectionStart()public void setSelectionStart(int selectionStart)public int getSelectionEnd()public void setSelectionEnd(int selectionEnd)public void select(int selectionStart, int selectionEnd)public void selectAll()The caret is the insertion point. It's where text appears when the user types. There are two methods to adjust it:public String getSelectedText()
public void setCaretPosition(int position)public int getCaretPosition()TextEvents
BothTextAreaandTextFieldcan install aTextListenerthat catchesTextEvents.TextComponents fireTextEvents every time the text of the component changes. This is more or less every time the user hits a key in the component.
Thejava.awt.event.TextListenerinterface defines a single method,textValueChanged():
You register apublic void textValueChanged(TextEvent te)TextListenerwith aTextComponentby calling the component'saddTextListener()method. For example,
TextArea password = new TextArea(24)However, most of the time it's sufficient to just get and set the text as you need it. It's really quite rare that you need to process it character by character.password.addTextListener(new PasswordChecker());
ATextListenercan be removed by callingremoveTextListener().
public void removeTextListener(TextListener tl)
java.awt.Canvas
Thejava.awt.Canvasclass is a rectangular area on which you can draw using the methods ofjava.awt.Graphicsdiscussed last week. TheCanvasclass has only three methods:
public Canvas()public void addNotify()You generally won't instantiate a canvas directly. Instead you'll subclass it and override thepublic void paint(Graphics g)paint()method in your subclass to draw the picture you want.
For example the followingCanvasdraws a big red oval you can add to your applet.
import java.awt.*;public class RedOval extends Canvas {public void paint(Graphics g) {Dimension d = this.getSize();g.setColor(Color.red);g.fillOval(0, 0, d.width, d.height);}public Dimension getMinimumSize() {return new Dimension(50, 100);}public Dimension getPreferredSize() {return new Dimension(150, 300);}public Dimension getMaximumSize() {return new Dimension(200, 400);}Any applet that uses components should not also override}paint(). Doing so will have unexpected effects because of the way Java arranges components. Instead, create aCanvasobject and do your drawing in itspaint()method.
Custom canvases are added to applets just like any other component. For example,
public void init() {this.add(new RedOval());Canvases themselves do not normally fire any events. Next week, we'll see how to change that in the subclasses.}
An alternate approach
import java.awt.*;public class ColoredOval extends Canvas {public ColoredOval() {this(Color.RED, 100, 100);}public ColoredOval(Color c) {this(c, 100, 100);}public ColoredOval(int width, int height) {this(Color.RED, width, height);}public ColoredOval(Color c, int width, int height) {this.setColor(c);this.setSize(width, height);}public void paint(Graphics g) {Dimension d = this.getSize();g.fillOval(0, 0, d.width, d.height);}This is almost but not quite the same effect as the previous applet. (It's a little less resizeable.)}
java.awt.Choice
Thejava.awt.Choiceclass implements a popup menu with a fixed position. (Thejava.awt.PopupMenuclass is a popup menu with no fixed position. It pops up when the user clicks
and holds the right mouse button.)
Creating a choice menu is a little more complex than creating the other user interface components you've seen. There's an extra step, adding the menu items to the menu. That is the five steps are
For example
- Declare the
Choice- Allocate the
Choice- Add the menu items to the
Choice- Add the
Choiceto thelayout- Add an
ItemListenerto theChoice
public void init() {Choice ch;ch = new Choice();ch.addItem("1");ch.addItem("2");ch.addItem("3");ch.addItem("4");ch.addItem("5");add(ch);}Methods of java.awt.Choice
TheChoiceclass has a number of methods to add, remove, and return different items from the list. The list starts counting at 0.
public int getItemCount()public String getItem(int index)public void add(String item)public void addItem(String item)public void insert(String item, int position)public void remove(String item)public void remove(int position)However, most of the item you'll just build thepublic void removeAll()Choicewhen the applet starts up, and not modify it later.
These methods get or set the current selected item in theChoice, that is the item that's shown.
public void removeAll()public String getSelectedItem()public Object[] getSelectedObjects()public int getSelectedIndex()public void select(int position)public void select(String item)ItemListeners
When the user changes the selected item in aChoice, theChoicefires twoItemListenerevents, one to indicate that the original selection has been deselected and the other to indicate that a new selection has been made. You can process these events by registering anItemListenerobject with yourChoice.
You do not always need to do this. It is not uncommon to only check the value of aChoicewhen some other event occurs like aButtonpress.
For example, the following applet builds aChoicemenu with the numbers from 1 to 5. When the user makes a selection, the applet beeps that many times.
import java.applet.*;import java.awt.*;import java.awt.event.*;public class MultiBeep extends Applet {public void init() {Choice ch;ch = new Choice();ch.addItem("1");ch.addItem("2");ch.addItem("3");ch.addItem("4");ch.addItem("5");this.add(ch);ch.addItemListener(new BeepItem());}}class BeepItem implements ItemListener {public void itemStateChanged(ItemEvent ie) {if (ie.getStateChange() == ItemEvent.SELECTED) {String name = (String) ie.getItem();Toolkit tk = Toolkit.getDefaultToolkit();try {int n = Integer.parseInt(name);for (int i = 0; i < n; i++) tk.beep();}catch (Exception e) {tk.beep();}}}}TheBeepItemclass implements theItemListenerinterface. It filters out events caused by items being deselected withItemEvent.getStateChange()and only beeps if an item was selected. The available convenience constants you can check are:ItemEvent.DESELECTEDItemEvent.ITEM_FIRSTItemEvent.ITEM_LASTItemEvent.ITEM_STATE_CHANGEDItemEvent.SELECTEDTheItemEvent.getItem()method is used to retrieve the actual selected item.java.awt.Checkbox
Check boxes are used to select abooleanvalue. EachCheckboxhas a label that should be used to tell the user what theCheckboxrepresents. For instance aCheckboxwith the label "Anchovies" would be checked if the user wants anchovies on their pizza and unchecked if they don't.
Checkboxes are often used to select from a list of possible choices when as few selections as zero or as many as everything on the list may be made. Adding aCheckboxto an applet is simple. Just declare it, construct it and add it.
Checkbox c c = new Checkbox("Pepperoni"));As usual these steps may be combined into the single lineadd(c);
add(new Checkbox("Pepperoni"));
By default check boxes are unchecked when created. If you want aCheckboxto start life checked, use the following constructor instead:
add(new Checkbox("Pepperoni", null, true));
Thenullis a reference to aCheckboxGroup. Passingnullfor this argument says that thisCheckboxdoes not belong to aCheckboxGroup.
EveryCheckboxhas abooleanvalue, eithertrueorfalse. When theCheckboxis checked that value istrue. When it is unchecked that value is false. You access this value using theCheckbox'sgetState()andsetState(boolean b)methods. For example
private void handleCheckbox(Checkbox c) {if (c.getState()) price += 0.50;else price -= 0.50;}Checkbox Events
When the aCheckboxchanges state, normally as a result of user action, it fires anItemEvent. Most of the time you ignore this event. Instead you manually check the state of aCheckboxwhen you need to know it. However if you want to know immediately when aCheckboxchanges state, you can register anItemListenerfor theCheckbox.
AnItemEventis exactly the same as the item event fired by aChoice. In fact item events are used to indicate selections or deselections in any sort of list including checkboxes, radio buttons, choices, and lists.
For example, the following program is an applet that asks the age-old question, "What do you want on your pizza?" When an ingredient is checked the price of the pizza goes up by fifty cents. When an ingredient is unchecked fifty cents is taken off. The price is shown in aTextField.
![]()
import java.applet.*;import java.awt.*;import java.awt.event.*;public class Ingredients extends Applet {private TextField display;private double price = 7.00;public void init() {this.add(new Label("What do you want on your pizza?", Label.CENTER));Pricer p = new Pricer(this);Checkbox pepperoni = new Checkbox("Pepperoni");this.add(pepperoni);pepperoni.addItemListener(p);Checkbox olives = new Checkbox("Olives");olives.addItemListener(p);this.add(olives);Checkbox onions = new Checkbox("Onions");onions.addItemListener(p);this.add(onions);Checkbox sausage = new Checkbox("Sausage");sausage.addItemListener(p);this.add(sausage);Checkbox peppers = new Checkbox("Peppers");peppers.addItemListener(p);this.add(peppers);Checkbox extraCheese = new Checkbox("Extra Cheese");extraCheese.addItemListener(p);this.add(extraCheese);Checkbox ham = new Checkbox("Ham");ham.addItemListener(p);this.add(ham);Checkbox pineapple = new Checkbox("Pineapple");pineapple.addItemListener(p);this.add(pineapplec);Checkbox anchovies = new Checkbox("Anchovies");anchovies.addItemListener(p);this.add(anchovies);this.display = new TextField(String.valueOf(price));// so people can't change the price of the pizzadisplay.setEditable(false);this.add(display);}public void setPrice(double price) {this.price = price;display.setText(String.valueOf(price));}public double getPrice() {return this.price;}}class Pricer implements ItemListener {private Ingredients out;public Pricer(Ingredients out) {this.out = out;}public void itemStateChanged(ItemEvent ie) {double price = out.getPrice();if (ie.getStateChange() == ItemEvent.SELECTED) price += 0.50;else price -= 0.50;// Change the priceout.setPrice(price);}}java.awt.CheckboxGroup
Checkbox groups are collections of checkboxes with the special property that no more than one checkbox in the same group can be selected at a time. The checkboxes in aCheckboxGroupare often called radio buttons. Checkboxes that are members of the sameCheckboxGroupcannot be checked simultaneously. When the user checks one, all others are unchecked automatically.
The constructor for aCheckboxGroupis trivial. No arguments are needed. You do not even need to add theCheckboxGroupto the applet since checkbox groups are themselves not user-interface widgets, just ways of arranging checkboxes.
CheckboxGroup cbg = new CheckboxGroup();
To make check boxes act like radio buttons, use this constructor for eachCheckboxin the group.
public Checkbox(String label, CheckboxGroup cbg, boolean checked)
The label is the label for thisCheckbox. TheCheckboxGroupis the group you want thisCheckboxto belong to and must already exist.
At any time, you can get or set the selectedCheckboxwith these two methods:
public Checkbox getSelectedCheckbox()public void setSelectedCheckbox(Checkbox box)java.awt.CheckboxGroup example
The following program asks the customer how they're going to pay for their pizza, Visa, Mastercard, American Express, Discover, cash or check. Someone may want both anchovies and pineapple on their pizza, but they're unlikely to pay with both Visa and American Express.
![]()
import java.applet.*;import java.awt.*;public class PaymentMethod extends Applet {public void init() {this.add(new Label("How will you pay for your pizza?"));CheckboxGroup cbg = new CheckboxGroup();this.add(new Checkbox("Visa", cbg, false));this.add(new Checkbox("Mastercard", cbg, false));this.add(new Checkbox("American Express", cbg, false));this.add(new Checkbox("Discover", cbg, false));this.add(new Checkbox("Cash", cbg, true)); // the default}There isn't any action in this simple example applet. If you need to add action as radio buttons are checked and unchecked, you do it just the same as for any other}Checkbox.
java.awt.List
Scrolling lists are useful for storing long lists of things one to a line. The things in the list are called items, but each one is just a String. For example,
List Methods
You create a newListwith one of these three constructors:
public List()public List(int numLines)For example,public List(int numLines, boolean allowMultipleSelections)
List l = new List(8, true);
numLinesis the number of items you want to be visible in the scrolling list. It is not necessarily the same as the number of items in the list which is limited only by available memory.allowMultipleSelectionssays whether the user is allowed to select more than one item at once (typically by Shift-clicking).
The following methods add items at the end of the list:
public void add(String item)These two methods add items at the specified position in the list.public void addItem(String item)
public void add(String item, int index)The following methods remove items from thepublic void addItem(String item, int index)List:
public void removeAll()public void remove(String item)public void remove(int position)public void delItem(int position)These methods allow you to retrive particular items from theList:public int getItemCount()public String getItem(int index)You ran also replace a particular item:public String[] getItems()
These methods allow you to determine which item the user has selected:public void replaceItem(String newValue, int index)
public int getSelectedIndex()public int[] getSelectedIndexes()public String getSelectedItem()public String[] getSelectedItems()If a list allows multiple selections, you should use the plural forms of the above methods. You can determine whether multiple selections are allowed withpublic Object[] getSelectedObjects()isMultipleMode()and change it withsetMultipleMode().
public boolean isMultipleMode()These methods allow you to manipulate the selection:public void setMultipleMode(boolean b)
public void select(int index)public void deselect(int index)These two methods determine whether an item at a particular index is currently visible in the List box:public boolean isIndexSelected(int index)
public int getVisibleIndex()public void makeVisible(int index)List Events
Lists can fire two separate types of events. When a list item is selected or deselected, theListfires anItemEvent. However, when the user double clicks on a list item, theListfires anActionEvent. Therefore, you can register both anItemListenerto process selections and/or anActionListenerto process double clicks.
public void addItemListener(ItemListener l)public void removeItemListener(ItemListener l)public void addActionListener(ActionListener l)The action command in thepublic void removeActionListener(ActionListener l)ActionEventis the list item which was double clicked.
java.awt.Scrollbar
Lists,TextAreas, andScrollPanes come with ready made scrollbars. However if you want to scroll any other object you'll have to use ajava.awt.Scrollbar. Scrollbars have many uses. At their most basic they're used for moving the visible area. They can also be used to set a value between two numbers. Or they can be used to flip through a number of screens as in a database operation that looks at successive records.
There are three constructors:
public Scrollbar()public Scrollbar(int orientation)Thepublic Scrollbar(int orientation, int value, int visible, int min, int max)orientationargument is one of the mnemonic constants,Scrollbar.HORIZONTALorScrollbar.VERTICAL. As you expect this determines whether theScrollbaris laid out from left to right or top to bottom.
AScrollbarhas anintvalue at all times. This value will be between theminimumand themaximumvalue set by the last two arguments to the constructor. When aScrollbaris created, its value is given by thevalueargument. The default is 0.
Finallyvisiblerepresents the size of the visible portion of the scrollable area in pixels. TheScrollbaruses this when moving up or down a page.
AScrollbarfires an adjustment event when its value changes. You register an adjustment listener to catch this event. This class needs anadjustmentValueChanged()method with this signature:
public void adjustmentValueChanged(AdjustmentEvent e)
The following program is an applet that changes the number in aTextFieldbetween 1 and 100 based on the position of the thumb (the movable part of theScrollbar). In a practical application the number would of course mean something.
import java.applet.*;import java.awt.*;import java.awt.event.*;public class Scrollie extends Applet implements AdjustmentListener {private TextField t;private Scrollbar sb;public void init() {int initialValue = 1;sb = new Scrollbar(Scrollbar.HORIZONTAL, initialValue, 100, 1, 100);sb.addAdjustmentListener(this);this.add(sb);this.t = new TextField(4);this.t.setText(String.valueOf(initialValue));this.add(t);}public void adjustmentValueChanged(AdjustmentEvent e)int val = sb.getValue();this.t.setText(String.valueOf(val));}}Peer vs. Swing Components
I'm not going to talk much about Swing in this course, but most of what I teach you about the standard AWT components carries over to their Swing equivalents with only trivial changes. For example, here's yet another way to write an applet that says "Cub Scouts!" in 24 point, SansSerif, bold and blue and with a yellow background.
import java.awt.*;import javax.swing.*;public class SwingCubScout extends JApplet {public void init() {JLabel cubScouts = new JLabel("Cub Scouts!");cubScouts.setForeground(Color.blue);cubScouts.setBackground(Color.yellow);cubScouts.setFont(new Font("Sans", Font.BOLD, 24));this.getContentPane().add(cubScouts);}This is almost identical to the AWT-based Cub Scout applet, except that I've imported the}javax.swingpackage and changedLabeltoJLabelandApplettoJApplet.
Week 6 Exercises
- Write an applet that with a 60 column by 10 row text area that allows the user to type some text. Add a button to this applet that clears the text area when it's pressed.
Don't worry excessively about making the applet look good. Before you can do that you'll need to learn about layout managers.
- Rewrite the payroll problem from week 2 as an applet. Provide a text field for the number of hours, a text field for the pay rate, and a non-editable text field for the output. Also provide labels to identify all three text fields and a button to calculate the result.
Don't worry about minimum wage, number of hours in the week, or other error conditions we checked before. In the event the user enters data that cannot be interpreted as a number, don't put anything in the output text field. In a couple of weeks, you'll learn how to bring up an error dialog to handle these conditions.Don't worry excessively about making the applet look good. Before you can do that you'll need to learn about layout managers. We'll cover them next weekGetting into more fun Graphicsimport java.awt.*;import java.awt.event.*;import javax.swing.*;public class ShowColors2 extends JFrame {private JButton changeColorButton;private Color color = Color.LIGHT_GRAY;private Container container;// set up GUIpublic ShowColors2(){super( "Using JColorChooser" );container = getContentPane();container.setLayout( new FlowLayout() );// set up changeColorButton and register its event handlerchangeColorButton = new JButton( "Change Color" );changeColorButton.addActionListener(new ActionListener() { // anonymous inner class// display JColorChooser when user clicks buttonpublic void actionPerformed( ActionEvent event ){color = JColorChooser.showDialog(ShowColors2.this, "Choose a color", color );// set default color, if no color is returnedif ( color == null )color = Color.LIGHT_GRAY;// change content pane's background colorcontainer.setBackground( color );}} // end anonymous inner class); // end call to addActionListenercontainer.add( changeColorButton );setSize( 400, 130 );setVisible( true );} // end ShowColor2 constructor// execute applicationpublic static void main( String args[] ){ShowColors2 application = new ShowColors2();application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );}}import java.awt.*;import java.awt.geom.*;import javax.swing.*;public class Shapes2 extends JFrame {// set window's title bar String, background color and dimensionspublic Shapes2(){super( "Drawing 2D Shapes" );getContentPane().setBackground( Color.WHITE );setSize( 400, 400 );setVisible( true );}// draw general pathspublic void paint( Graphics g ){super.paint( g ); // call superclass's paint methodint xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };Graphics2D g2d = ( Graphics2D ) g;GeneralPath star = new GeneralPath(); // create GeneralPath object// set the initial coordinate of the General Pathstar.moveTo( xPoints[ 0 ], yPoints[ 0 ] );// create the star--this does not draw the starfor ( int count = 1; count < xPoints.length; count++ )star.lineTo( xPoints[ count ], yPoints[ count ] );star.closePath(); // close the shapeg2d.translate( 200, 200 ); // translate the origin to (200, 200)// rotate around origin and draw stars in random colorsfor ( int count = 1; count <= 20; count++ ) {g2d.rotate( Math.PI / 10.0 ); // rotate coordinate system// set random drawing colorg2d.setColor( new Color( ( int ) ( Math.random() * 256 ),( int ) ( Math.random() * 256 ),( int ) ( Math.random() * 256 ) ) );g2d.fill( star ); // draw filled star}} // end method paint// execute applicationpublic static void main( String args[] ){Shapes2 application = new Shapes2();application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );}}
An example of text fields in Java
The following applet reads text from oneTextFieldand capitalizes it in anotherTextField.
![]()
import java.applet.*;import java.awt.*;import java.awt.event.*;public class CapitalizeApplet extends Applet {private TextField input;private TextField output;public void init () {// Construct the TextFieldsthis.input = new TextField(40);this.output = new TextField(40);this.output.setEditable(false);Button b = new Button("Capitalize");// add the button to the layoutthis.add(input);this.add(b);this.add(output);// specify that action events sent by the// button or the input TextField should be handled// by the same CapitalizerAction objectCapitalizerAction ca = new CapitalizerAction(input, output);b.addActionListener(ca);this.input.addActionListener(ca);// notice that ActionEvents produced by output are ignored.}}class CapitalizerAction implements ActionListener {private TextField in;private TextField out;public CapitalizerAction(TextField in, TextField out) {this.in = in;this.out = out;}public void actionPerformed(ActionEvent ae) {String s = in.getText();out.setText(s.toUpperCase());}In this program, a different pattern is used for handling events. The constructor for the}CapitalizerActionclass is used to pass in references to the different components theactionPerformed()method affects.
An example of text fields in Java
An alternate pattern uses an inner class so the private fields can be accessed directly.
import java.applet.*;import java.awt.*;import java.awt.event.*;public class CapitalizeApplet extends Applet {private TextField input;private TextField output;public void init () {// Construct the TextFieldsthis.input = new TextField(40);this.output = new TextField(40);this.output.setEditable(false);Button b = new Button("Capitalize");// add the button to the layoutthis.add(input);this.add(b);this.add(output);// specify that action events sent by the// button or the input TextField should be handled// by the same CapitalizerAction objectCapitalizerAction ca = new CapitalizerAction();b.addActionListener(ca);this.input.addActionListener(ca);// notice that ActionEvents produced by output are ignored.}class CapitalizerAction implements ActionListener {public void actionPerformed(ActionEvent ae) {String s = input.getText();output.setText(s.toUpperCase());}}}TextArea
Thejava.awt.TextAreaclass is a subclass ofjava.awt.TextComponentthat provides a widget for editing multiple lines of text. It's useful for input and output.
There are five constructors:
public TextArea()public TextArea(String text)public TextArea(int rows, int columns)public TextArea(String text, int rows, int columns)Because of the way Java lays out components, you should not use the noargs constructor. Either start off with apublic TextArea(String text, int rows, int columns, int scrollbars)Stringor specify the number of rows and columns this area is expected to hold. For example,
By default, TextAreas don't have scrollbars. However you can add them by passing one of these constants to the constructor:TextArea address = new TextArea("Type your address here", 5, 80);
TextArea.SCROLLBARS_BOTHTextArea.SCROLLBARS_HORIZONTAL_ONLYTextArea.SCROLLBARS_NONEFor example,TextArea.SCROLLBARS_VERTICAL_ONLY
TextArea instructions =Unlike text fields, text areas do not generate action events when the user hits return inside the area. Instead, the line is broken and the caret moves on to the next row.new TextArea("", 15, 70, TextArea.SCROLLBARS_VERTICAL_ONLY);
However, thegetText()method does return the contents of theTextArea, and thesetText()method does change it. ThesetEditable()method lets you determine whether or not, the user can modify the contents of aTextField. If these methods sound familiar it's because they're both inherited from the common superclass ofTextFieldandTextArea,TextComponent.
Furthermore, you can append text to aTextAreawith theappend()method, insert text into the middle of aTextAreawith theinsert()method, and replace a block of text with thereplaceRange()method:
public void insert(String text, int position)public void append(String text)public void replaceRange(String text, int start, int end)TextComponent
BothTextAreaandTextFieldare subclasses ofjava.awt.TextComponent. This class contains methods common to both classes including several you've already seen:getText(),setText(), andsetEditable(). TheTextComponentclass also defines methods for manipulating the selection and the caret and for processingTextEvents.
The selection is used for copy and paste and other purposes. The first character in aTextComponentis character 0; the second is character 1, and so on.
public int getSelectionStart()public void setSelectionStart(int selectionStart)public int getSelectionEnd()public void setSelectionEnd(int selectionEnd)public void select(int selectionStart, int selectionEnd)public void selectAll()The caret is the insertion point. It's where text appears when the user types. There are two methods to adjust it:public String getSelectedText()
public void setCaretPosition(int position)public int getCaretPosition()TextEvents
BothTextAreaandTextFieldcan install aTextListenerthat catchesTextEvents.TextComponents fireTextEvents every time the text of the component changes. This is more or less every time the user hits a key in the component.
Thejava.awt.event.TextListenerinterface defines a single method,textValueChanged():
You register apublic void textValueChanged(TextEvent te)TextListenerwith aTextComponentby calling the component'saddTextListener()method. For example,
TextArea password = new TextArea(24)However, most of the time it's sufficient to just get and set the text as you need it. It's really quite rare that you need to process it character by character.password.addTextListener(new PasswordChecker());
ATextListenercan be removed by callingremoveTextListener().
public void removeTextListener(TextListener tl)
java.awt.Canvas
Thejava.awt.Canvasclass is a rectangular area on which you can draw using the methods ofjava.awt.Graphicsdiscussed last week. TheCanvasclass has only three methods:
public Canvas()public void addNotify()You generally won't instantiate a canvas directly. Instead you'll subclass it and override thepublic void paint(Graphics g)paint()method in your subclass to draw the picture you want.
For example the followingCanvasdraws a big red oval you can add to your applet.
import java.awt.*;public class RedOval extends Canvas {public void paint(Graphics g) {Dimension d = this.getSize();g.setColor(Color.red);g.fillOval(0, 0, d.width, d.height);}public Dimension getMinimumSize() {return new Dimension(50, 100);}public Dimension getPreferredSize() {return new Dimension(150, 300);}public Dimension getMaximumSize() {return new Dimension(200, 400);}Any applet that uses components should not also override}paint(). Doing so will have unexpected effects because of the way Java arranges components. Instead, create aCanvasobject and do your drawing in itspaint()method.
Custom canvases are added to applets just like any other component. For example,
public void init() {this.add(new RedOval());Canvases themselves do not normally fire any events. Next week, we'll see how to change that in the subclasses.}
An alternate approach
import java.awt.*;public class ColoredOval extends Canvas {public ColoredOval() {this(Color.RED, 100, 100);}public ColoredOval(Color c) {this(c, 100, 100);}public ColoredOval(int width, int height) {this(Color.RED, width, height);}public ColoredOval(Color c, int width, int height) {this.setColor(c);this.setSize(width, height);}public void paint(Graphics g) {Dimension d = this.getSize();g.fillOval(0, 0, d.width, d.height);}This is almost but not quite the same effect as the previous applet. (It's a little less resizeable.)}
java.awt.Choice
Thejava.awt.Choiceclass implements a popup menu with a fixed position. (Thejava.awt.PopupMenuclass is a popup menu with no fixed position. It pops up when the user clicks
and holds the right mouse button.)
Creating a choice menu is a little more complex than creating the other user interface components you've seen. There's an extra step, adding the menu items to the menu. That is the five steps are
For example
- Declare the
Choice- Allocate the
Choice- Add the menu items to the
Choice- Add the
Choiceto thelayout- Add an
ItemListenerto theChoice
public void init() {Choice ch;ch = new Choice();ch.addItem("1");ch.addItem("2");ch.addItem("3");ch.addItem("4");ch.addItem("5");add(ch);}Methods of java.awt.Choice
TheChoiceclass has a number of methods to add, remove, and return different items from the list. The list starts counting at 0.
public int getItemCount()public String getItem(int index)public void add(String item)public void addItem(String item)public void insert(String item, int position)public void remove(String item)public void remove(int position)However, most of the item you'll just build thepublic void removeAll()Choicewhen the applet starts up, and not modify it later.
These methods get or set the current selected item in theChoice, that is the item that's shown.
public void removeAll()public String getSelectedItem()public Object[] getSelectedObjects()public int getSelectedIndex()public void select(int position)public void select(String item)ItemListeners
When the user changes the selected item in aChoice, theChoicefires twoItemListenerevents, one to indicate that the original selection has been deselected and the other to indicate that a new selection has been made. You can process these events by registering anItemListenerobject with yourChoice.
You do not always need to do this. It is not uncommon to only check the value of aChoicewhen some other event occurs like aButtonpress.
For example, the following applet builds aChoicemenu with the numbers from 1 to 5. When the user makes a selection, the applet beeps that many times.
import java.applet.*;import java.awt.*;import java.awt.event.*;public class MultiBeep extends Applet {public void init() {Choice ch;ch = new Choice();ch.addItem("1");ch.addItem("2");ch.addItem("3");ch.addItem("4");ch.addItem("5");this.add(ch);ch.addItemListener(new BeepItem());}}class BeepItem implements ItemListener {public void itemStateChanged(ItemEvent ie) {if (ie.getStateChange() == ItemEvent.SELECTED) {String name = (String) ie.getItem();Toolkit tk = Toolkit.getDefaultToolkit();try {int n = Integer.parseInt(name);for (int i = 0; i < n; i++) tk.beep();}catch (Exception e) {tk.beep();}}}}TheBeepItemclass implements theItemListenerinterface. It filters out events caused by items being deselected withItemEvent.getStateChange()and only beeps if an item was selected. The available convenience constants you can check are:ItemEvent.DESELECTEDItemEvent.ITEM_FIRSTItemEvent.ITEM_LASTItemEvent.ITEM_STATE_CHANGEDItemEvent.SELECTEDTheItemEvent.getItem()method is used to retrieve the actual selected item.java.awt.Checkbox
Check boxes are used to select abooleanvalue. EachCheckboxhas a label that should be used to tell the user what theCheckboxrepresents. For instance aCheckboxwith the label "Anchovies" would be checked if the user wants anchovies on their pizza and unchecked if they don't.
Checkboxes are often used to select from a list of possible choices when as few selections as zero or as many as everything on the list may be made. Adding aCheckboxto an applet is simple. Just declare it, construct it and add it.
Checkbox c c = new Checkbox("Pepperoni"));As usual these steps may be combined into the single lineadd(c);
add(new Checkbox("Pepperoni"));
By default check boxes are unchecked when created. If you want aCheckboxto start life checked, use the following constructor instead:
add(new Checkbox("Pepperoni", null, true));
Thenullis a reference to aCheckboxGroup. Passingnullfor this argument says that thisCheckboxdoes not belong to aCheckboxGroup.
EveryCheckboxhas abooleanvalue, eithertrueorfalse. When theCheckboxis checked that value istrue. When it is unchecked that value is false. You access this value using theCheckbox'sgetState()andsetState(boolean b)methods. For example
private void handleCheckbox(Checkbox c) {if (c.getState()) price += 0.50;else price -= 0.50;}Checkbox Events
When the aCheckboxchanges state, normally as a result of user action, it fires anItemEvent. Most of the time you ignore this event. Instead you manually check the state of aCheckboxwhen you need to know it. However if you want to know immediately when aCheckboxchanges state, you can register anItemListenerfor theCheckbox.
AnItemEventis exactly the same as the item event fired by aChoice. In fact item events are used to indicate selections or deselections in any sort of list including checkboxes, radio buttons, choices, and lists.
For example, the following program is an applet that asks the age-old question, "What do you want on your pizza?" When an ingredient is checked the price of the pizza goes up by fifty cents. When an ingredient is unchecked fifty cents is taken off. The price is shown in aTextField.
![]()
import java.applet.*;import java.awt.*;import java.awt.event.*;public class Ingredients extends Applet {private TextField display;private double price = 7.00;public void init() {this.add(new Label("What do you want on your pizza?", Label.CENTER));Pricer p = new Pricer(this);Checkbox pepperoni = new Checkbox("Pepperoni");this.add(pepperoni);pepperoni.addItemListener(p);Checkbox olives = new Checkbox("Olives");olives.addItemListener(p);this.add(olives);Checkbox onions = new Checkbox("Onions");onions.addItemListener(p);this.add(onions);Checkbox sausage = new Checkbox("Sausage");sausage.addItemListener(p);this.add(sausage);Checkbox peppers = new Checkbox("Peppers");peppers.addItemListener(p);this.add(peppers);Checkbox extraCheese = new Checkbox("Extra Cheese");extraCheese.addItemListener(p);this.add(extraCheese);Checkbox ham = new Checkbox("Ham");ham.addItemListener(p);this.add(ham);Checkbox pineapple = new Checkbox("Pineapple");pineapple.addItemListener(p);this.add(pineapplec);Checkbox anchovies = new Checkbox("Anchovies");anchovies.addItemListener(p);this.add(anchovies);this.display = new TextField(String.valueOf(price));// so people can't change the price of the pizzadisplay.setEditable(false);this.add(display);}public void setPrice(double price) {this.price = price;display.setText(String.valueOf(price));}public double getPrice() {return this.price;}}class Pricer implements ItemListener {private Ingredients out;public Pricer(Ingredients out) {this.out = out;}public void itemStateChanged(ItemEvent ie) {double price = out.getPrice();if (ie.getStateChange() == ItemEvent.SELECTED) price += 0.50;else price -= 0.50;// Change the priceout.setPrice(price);}}java.awt.CheckboxGroup
Checkbox groups are collections of checkboxes with the special property that no more than one checkbox in the same group can be selected at a time. The checkboxes in aCheckboxGroupare often called radio buttons. Checkboxes that are members of the sameCheckboxGroupcannot be checked simultaneously. When the user checks one, all others are unchecked automatically.
The constructor for aCheckboxGroupis trivial. No arguments are needed. You do not even need to add theCheckboxGroupto the applet since checkbox groups are themselves not user-interface widgets, just ways of arranging checkboxes.
CheckboxGroup cbg = new CheckboxGroup();
To make check boxes act like radio buttons, use this constructor for eachCheckboxin the group.
public Checkbox(String label, CheckboxGroup cbg, boolean checked)
The label is the label for thisCheckbox. TheCheckboxGroupis the group you want thisCheckboxto belong to and must already exist.
At any time, you can get or set the selectedCheckboxwith these two methods:
public Checkbox getSelectedCheckbox()public void setSelectedCheckbox(Checkbox box)java.awt.CheckboxGroup example
The following program asks the customer how they're going to pay for their pizza, Visa, Mastercard, American Express, Discover, cash or check. Someone may want both anchovies and pineapple on their pizza, but they're unlikely to pay with both Visa and American Express.
![]()
import java.applet.*;import java.awt.*;public class PaymentMethod extends Applet {public void init() {this.add(new Label("How will you pay for your pizza?"));CheckboxGroup cbg = new CheckboxGroup();this.add(new Checkbox("Visa", cbg, false));this.add(new Checkbox("Mastercard", cbg, false));this.add(new Checkbox("American Express", cbg, false));this.add(new Checkbox("Discover", cbg, false));this.add(new Checkbox("Cash", cbg, true)); // the default}There isn't any action in this simple example applet. If you need to add action as radio buttons are checked and unchecked, you do it just the same as for any other}Checkbox.
java.awt.List
Scrolling lists are useful for storing long lists of things one to a line. The things in the list are called items, but each one is just a String. For example,
List Methods
You create a newListwith one of these three constructors:
public List()public List(int numLines)For example,public List(int numLines, boolean allowMultipleSelections)
List l = new List(8, true);
numLinesis the number of items you want to be visible in the scrolling list. It is not necessarily the same as the number of items in the list which is limited only by available memory.allowMultipleSelectionssays whether the user is allowed to select more than one item at once (typically by Shift-clicking).
The following methods add items at the end of the list:
public void add(String item)These two methods add items at the specified position in the list.public void addItem(String item)
public void add(String item, int index)The following methods remove items from thepublic void addItem(String item, int index)List:
public void removeAll()public void remove(String item)public void remove(int position)public void delItem(int position)These methods allow you to retrive particular items from theList:public int getItemCount()public String getItem(int index)You ran also replace a particular item:public String[] getItems()
These methods allow you to determine which item the user has selected:public void replaceItem(String newValue, int index)
public int getSelectedIndex()public int[] getSelectedIndexes()public String getSelectedItem()public String[] getSelectedItems()If a list allows multiple selections, you should use the plural forms of the above methods. You can determine whether multiple selections are allowed withpublic Object[] getSelectedObjects()isMultipleMode()and change it withsetMultipleMode().
public boolean isMultipleMode()These methods allow you to manipulate the selection:public void setMultipleMode(boolean b)
public void select(int index)public void deselect(int index)These two methods determine whether an item at a particular index is currently visible in the List box:public boolean isIndexSelected(int index)
public int getVisibleIndex()public void makeVisible(int index)List Events
Lists can fire two separate types of events. When a list item is selected or deselected, theListfires anItemEvent. However, when the user double clicks on a list item, theListfires anActionEvent. Therefore, you can register both anItemListenerto process selections and/or anActionListenerto process double clicks.
public void addItemListener(ItemListener l)public void removeItemListener(ItemListener l)public void addActionListener(ActionListener l)The action command in thepublic void removeActionListener(ActionListener l)ActionEventis the list item which was double clicked.
java.awt.Scrollbar
Lists,TextAreas, andScrollPanes come with ready made scrollbars. However if you want to scroll any other object you'll have to use ajava.awt.Scrollbar. Scrollbars have many uses. At their most basic they're used for moving the visible area. They can also be used to set a value between two numbers. Or they can be used to flip through a number of screens as in a database operation that looks at successive records.
There are three constructors:
public Scrollbar()public Scrollbar(int orientation)Thepublic Scrollbar(int orientation, int value, int visible, int min, int max)orientationargument is one of the mnemonic constants,Scrollbar.HORIZONTALorScrollbar.VERTICAL. As you expect this determines whether theScrollbaris laid out from left to right or top to bottom.
AScrollbarhas anintvalue at all times. This value will be between theminimumand themaximumvalue set by the last two arguments to the constructor. When aScrollbaris created, its value is given by thevalueargument. The default is 0.
Finallyvisiblerepresents the size of the visible portion of the scrollable area in pixels. TheScrollbaruses this when moving up or down a page.
AScrollbarfires an adjustment event when its value changes. You register an adjustment listener to catch this event. This class needs anadjustmentValueChanged()method with this signature:
public void adjustmentValueChanged(AdjustmentEvent e)
The following program is an applet that changes the number in aTextFieldbetween 1 and 100 based on the position of the thumb (the movable part of theScrollbar). In a practical application the number would of course mean something.
import java.applet.*;import java.awt.*;import java.awt.event.*;public class Scrollie extends Applet implements AdjustmentListener {private TextField t;private Scrollbar sb;public void init() {int initialValue = 1;sb = new Scrollbar(Scrollbar.HORIZONTAL, initialValue, 100, 1, 100);sb.addAdjustmentListener(this);this.add(sb);this.t = new TextField(4);this.t.setText(String.valueOf(initialValue));this.add(t);}public void adjustmentValueChanged(AdjustmentEvent e)int val = sb.getValue();this.t.setText(String.valueOf(val));}}Peer vs. Swing Components
I'm not going to talk much about Swing in this course, but most of what I teach you about the standard AWT components carries over to their Swing equivalents with only trivial changes. For example, here's yet another way to write an applet that says "Cub Scouts!" in 24 point, SansSerif, bold and blue and with a yellow background.
import java.awt.*;import javax.swing.*;public class SwingCubScout extends JApplet {public void init() {JLabel cubScouts = new JLabel("Cub Scouts!");cubScouts.setForeground(Color.blue);cubScouts.setBackground(Color.yellow);cubScouts.setFont(new Font("Sans", Font.BOLD, 24));this.getContentPane().add(cubScouts);}This is almost identical to the AWT-based Cub Scout applet, except that I've imported the}javax.swingpackage and changedLabeltoJLabelandApplettoJApplet.
Week 6 Exercises
- Write an applet that with a 60 column by 10 row text area that allows the user to type some text. Add a button to this applet that clears the text area when it's pressed.
Don't worry excessively about making the applet look good. Before you can do that you'll need to learn about layout managers.
- Rewrite the payroll problem from week 2 as an applet. Provide a text field for the number of hours, a text field for the pay rate, and a non-editable text field for the output. Also provide labels to identify all three text fields and a button to calculate the result.
Don't worry about minimum wage, number of hours in the week, or other error conditions we checked before. In the event the user enters data that cannot be interpreted as a number, don't put anything in the output text field. In a couple of weeks, you'll learn how to bring up an error dialog to handle these conditions.Don't worry excessively about making the applet look good. Before you can do that you'll need to learn about layout managers. We'll cover them next weekGetting into more fun Graphicsimport java.awt.*;import java.awt.event.*;import javax.swing.*;public class ShowColors2 extends JFrame {private JButton changeColorButton;private Color color = Color.LIGHT_GRAY;private Container container;// set up GUIpublic ShowColors2(){super( "Using JColorChooser" );container = getContentPane();container.setLayout( new FlowLayout() );// set up changeColorButton and register its event handlerchangeColorButton = new JButton( "Change Color" );changeColorButton.addActionListener(new ActionListener() { // anonymous inner class// display JColorChooser when user clicks buttonpublic void actionPerformed( ActionEvent event ){color = JColorChooser.showDialog(ShowColors2.this, "Choose a color", color );// set default color, if no color is returnedif ( color == null )color = Color.LIGHT_GRAY;// change content pane's background colorcontainer.setBackground( color );}} // end anonymous inner class); // end call to addActionListenercontainer.add( changeColorButton );setSize( 400, 130 );setVisible( true );} // end ShowColor2 constructor// execute applicationpublic static void main( String args[] ){ShowColors2 application = new ShowColors2();application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );}}import java.awt.*;import java.awt.geom.*;import javax.swing.*;public class Shapes2 extends JFrame {// set window's title bar String, background color and dimensionspublic Shapes2(){super( "Drawing 2D Shapes" );getContentPane().setBackground( Color.WHITE );setSize( 400, 400 );setVisible( true );}// draw general pathspublic void paint( Graphics g ){super.paint( g ); // call superclass's paint methodint xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };Graphics2D g2d = ( Graphics2D ) g;GeneralPath star = new GeneralPath(); // create GeneralPath object// set the initial coordinate of the General Pathstar.moveTo( xPoints[ 0 ], yPoints[ 0 ] );// create the star--this does not draw the starfor ( int count = 1; count < xPoints.length; count++ )star.lineTo( xPoints[ count ], yPoints[ count ] );star.closePath(); // close the shapeg2d.translate( 200, 200 ); // translate the origin to (200, 200)// rotate around origin and draw stars in random colorsfor ( int count = 1; count <= 20; count++ ) {g2d.rotate( Math.PI / 10.0 ); // rotate coordinate system// set random drawing colorg2d.setColor( new Color( ( int ) ( Math.random() * 256 ),( int ) ( Math.random() * 256 ),( int ) ( Math.random() * 256 ) ) );g2d.fill( star ); // draw filled star}} // end method paint// execute applicationpublic static void main( String args[] ){Shapes2 application = new Shapes2();application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );}}
An example of text fields in Java
The following applet reads text from oneTextFieldand capitalizes it in anotherTextField.
![]()
import java.applet.*;import java.awt.*;import java.awt.event.*;public class CapitalizeApplet extends Applet {private TextField input;private TextField output;public void init () {// Construct the TextFieldsthis.input = new TextField(40);this.output = new TextField(40);this.output.setEditable(false);Button b = new Button("Capitalize");// add the button to the layoutthis.add(input);this.add(b);this.add(output);// specify that action events sent by the// button or the input TextField should be handled// by the same CapitalizerAction objectCapitalizerAction ca = new CapitalizerAction(input, output);b.addActionListener(ca);this.input.addActionListener(ca);// notice that ActionEvents produced by output are ignored.}}class CapitalizerAction implements ActionListener {private TextField in;private TextField out;public CapitalizerAction(TextField in, TextField out) {this.in = in;this.out = out;}public void actionPerformed(ActionEvent ae) {String s = in.getText();out.setText(s.toUpperCase());}In this program, a different pattern is used for handling events. The constructor for the}CapitalizerActionclass is used to pass in references to the different components theactionPerformed()method affects.
An example of text fields in Java
An alternate pattern uses an inner class so the private fields can be accessed directly.
import java.applet.*;import java.awt.*;import java.awt.event.*;public class CapitalizeApplet extends Applet {private TextField input;private TextField output;public void init () {// Construct the TextFieldsthis.input = new TextField(40);this.output = new TextField(40);this.output.setEditable(false);Button b = new Button("Capitalize");// add the button to the layoutthis.add(input);this.add(b);this.add(output);// specify that action events sent by the// button or the input TextField should be handled// by the same CapitalizerAction objectCapitalizerAction ca = new CapitalizerAction();b.addActionListener(ca);this.input.addActionListener(ca);// notice that ActionEvents produced by output are ignored.}class CapitalizerAction implements ActionListener {public void actionPerformed(ActionEvent ae) {String s = input.getText();output.setText(s.toUpperCase());}}}TextArea
Thejava.awt.TextAreaclass is a subclass ofjava.awt.TextComponentthat provides a widget for editing multiple lines of text. It's useful for input and output.
There are five constructors:
public TextArea()public TextArea(String text)public TextArea(int rows, int columns)public TextArea(String text, int rows, int columns)Because of the way Java lays out components, you should not use the noargs constructor. Either start off with apublic TextArea(String text, int rows, int columns, int scrollbars)Stringor specify the number of rows and columns this area is expected to hold. For example,
By default, TextAreas don't have scrollbars. However you can add them by passing one of these constants to the constructor:TextArea address = new TextArea("Type your address here", 5, 80);
TextArea.SCROLLBARS_BOTHTextArea.SCROLLBARS_HORIZONTAL_ONLYTextArea.SCROLLBARS_NONEFor example,TextArea.SCROLLBARS_VERTICAL_ONLY
TextArea instructions =Unlike text fields, text areas do not generate action events when the user hits return inside the area. Instead, the line is broken and the caret moves on to the next row.new TextArea("", 15, 70, TextArea.SCROLLBARS_VERTICAL_ONLY);
However, thegetText()method does return the contents of theTextArea, and thesetText()method does change it. ThesetEditable()method lets you determine whether or not, the user can modify the contents of aTextField. If these methods sound familiar it's because they're both inherited from the common superclass ofTextFieldandTextArea,TextComponent.
Furthermore, you can append text to aTextAreawith theappend()method, insert text into the middle of aTextAreawith theinsert()method, and replace a block of text with thereplaceRange()method:
public void insert(String text, int position)public void append(String text)public void replaceRange(String text, int start, int end)TextComponent
BothTextAreaandTextFieldare subclasses ofjava.awt.TextComponent. This class contains methods common to both classes including several you've already seen:getText(),setText(), andsetEditable(). TheTextComponentclass also defines methods for manipulating the selection and the caret and for processingTextEvents.
The selection is used for copy and paste and other purposes. The first character in aTextComponentis character 0; the second is character 1, and so on.
public int getSelectionStart()public void setSelectionStart(int selectionStart)public int getSelectionEnd()public void setSelectionEnd(int selectionEnd)public void select(int selectionStart, int selectionEnd)public void selectAll()The caret is the insertion point. It's where text appears when the user types. There are two methods to adjust it:public String getSelectedText()
public void setCaretPosition(int position)public int getCaretPosition()TextEvents
BothTextAreaandTextFieldcan install aTextListenerthat catchesTextEvents.TextComponents fireTextEvents every time the text of the component changes. This is more or less every time the user hits a key in the component.
Thejava.awt.event.TextListenerinterface defines a single method,textValueChanged():
You register apublic void textValueChanged(TextEvent te)TextListenerwith aTextComponentby calling the component'saddTextListener()method. For example,
TextArea password = new TextArea(24)However, most of the time it's sufficient to just get and set the text as you need it. It's really quite rare that you need to process it character by character.password.addTextListener(new PasswordChecker());
ATextListenercan be removed by callingremoveTextListener().
public void removeTextListener(TextListener tl)
java.awt.Canvas
Thejava.awt.Canvasclass is a rectangular area on which you can draw using the methods ofjava.awt.Graphicsdiscussed last week. TheCanvasclass has only three methods:
public Canvas()public void addNotify()You generally won't instantiate a canvas directly. Instead you'll subclass it and override thepublic void paint(Graphics g)paint()method in your subclass to draw the picture you want.
For example the followingCanvasdraws a big red oval you can add to your applet.
import java.awt.*;public class RedOval extends Canvas {public void paint(Graphics g) {Dimension d = this.getSize();g.setColor(Color.red);g.fillOval(0, 0, d.width, d.height);}public Dimension getMinimumSize() {return new Dimension(50, 100);}public Dimension getPreferredSize() {return new Dimension(150, 300);}public Dimension getMaximumSize() {return new Dimension(200, 400);}Any applet that uses components should not also override}paint(). Doing so will have unexpected effects because of the way Java arranges components. Instead, create aCanvasobject and do your drawing in itspaint()method.
Custom canvases are added to applets just like any other component. For example,
public void init() {this.add(new RedOval());Canvases themselves do not normally fire any events. Next week, we'll see how to change that in the subclasses.}
An alternate approach
import java.awt.*;public class ColoredOval extends Canvas {public ColoredOval() {this(Color.RED, 100, 100);}public ColoredOval(Color c) {this(c, 100, 100);}public ColoredOval(int width, int height) {this(Color.RED, width, height);}public ColoredOval(Color c, int width, int height) {this.setColor(c);this.setSize(width, height);}public void paint(Graphics g) {Dimension d = this.getSize();g.fillOval(0, 0, d.width, d.height);}This is almost but not quite the same effect as the previous applet. (It's a little less resizeable.)}
java.awt.Choice
Thejava.awt.Choiceclass implements a popup menu with a fixed position. (Thejava.awt.PopupMenuclass is a popup menu with no fixed position. It pops up when the user clicks
and holds the right mouse button.)
Creating a choice menu is a little more complex than creating the other user interface components you've seen. There's an extra step, adding the menu items to the menu. That is the five steps are
For example
- Declare the
Choice- Allocate the
Choice- Add the menu items to the
Choice- Add the
Choiceto thelayout- Add an
ItemListenerto theChoice
public void init() {Choice ch;ch = new Choice();ch.addItem("1");ch.addItem("2");ch.addItem("3");ch.addItem("4");ch.addItem("5");add(ch);}Methods of java.awt.Choice
TheChoiceclass has a number of methods to add, remove, and return different items from the list. The list starts counting at 0.
public int getItemCount()public String getItem(int index)public void add(String item)public void addItem(String item)public void insert(String item, int position)public void remove(String item)public void remove(int position)However, most of the item you'll just build thepublic void removeAll()Choicewhen the applet starts up, and not modify it later.
These methods get or set the current selected item in theChoice, that is the item that's shown.
public void removeAll()public String getSelectedItem()public Object[] getSelectedObjects()public int getSelectedIndex()public void select(int position)public void select(String item)ItemListeners
When the user changes the selected item in aChoice, theChoicefires twoItemListenerevents, one to indicate that the original selection has been deselected and the other to indicate that a new selection has been made. You can process these events by registering anItemListenerobject with yourChoice.
You do not always need to do this. It is not uncommon to only check the value of aChoicewhen some other event occurs like aButtonpress.
For example, the following applet builds aChoicemenu with the numbers from 1 to 5. When the user makes a selection, the applet beeps that many times.
import java.applet.*;import java.awt.*;import java.awt.event.*;public class MultiBeep extends Applet {public void init() {Choice ch;ch = new Choice();ch.addItem("1");ch.addItem("2");ch.addItem("3");ch.addItem("4");ch.addItem("5");this.add(ch);ch.addItemListener(new BeepItem());}}class BeepItem implements ItemListener {public void itemStateChanged(ItemEvent ie) {if (ie.getStateChange() == ItemEvent.SELECTED) {String name = (String) ie.getItem();Toolkit tk = Toolkit.getDefaultToolkit();try {int n = Integer.parseInt(name);for (int i = 0; i < n; i++) tk.beep();}catch (Exception e) {tk.beep();}}}}TheBeepItemclass implements theItemListenerinterface. It filters out events caused by items being deselected withItemEvent.getStateChange()and only beeps if an item was selected. The available convenience constants you can check are:ItemEvent.DESELECTEDItemEvent.ITEM_FIRSTItemEvent.ITEM_LASTItemEvent.ITEM_STATE_CHANGEDItemEvent.SELECTEDTheItemEvent.getItem()method is used to retrieve the actual selected item.java.awt.Checkbox
Check boxes are used to select abooleanvalue. EachCheckboxhas a label that should be used to tell the user what theCheckboxrepresents. For instance aCheckboxwith the label "Anchovies" would be checked if the user wants anchovies on their pizza and unchecked if they don't.
Checkboxes are often used to select from a list of possible choices when as few selections as zero or as many as everything on the list may be made. Adding aCheckboxto an applet is simple. Just declare it, construct it and add it.
Checkbox c c = new Checkbox("Pepperoni"));As usual these steps may be combined into the single lineadd(c);
add(new Checkbox("Pepperoni"));
By default check boxes are unchecked when created. If you want aCheckboxto start life checked, use the following constructor instead:
add(new Checkbox("Pepperoni", null, true));
Thenullis a reference to aCheckboxGroup. Passingnullfor this argument says that thisCheckboxdoes not belong to aCheckboxGroup.
EveryCheckboxhas abooleanvalue, eithertrueorfalse. When theCheckboxis checked that value istrue. When it is unchecked that value is false. You access this value using theCheckbox'sgetState()andsetState(boolean b)methods. For example
private void handleCheckbox(Checkbox c) {if (c.getState()) price += 0.50;else price -= 0.50;}Checkbox Events
When the aCheckboxchanges state, normally as a result of user action, it fires anItemEvent. Most of the time you ignore this event. Instead you manually check the state of aCheckboxwhen you need to know it. However if you want to know immediately when aCheckboxchanges state, you can register anItemListenerfor theCheckbox.
AnItemEventis exactly the same as the item event fired by aChoice. In fact item events are used to indicate selections or deselections in any sort of list including checkboxes, radio buttons, choices, and lists.
For example, the following program is an applet that asks the age-old question, "What do you want on your pizza?" When an ingredient is checked the price of the pizza goes up by fifty cents. When an ingredient is unchecked fifty cents is taken off. The price is shown in aTextField.
![]()
import java.applet.*;import java.awt.*;import java.awt.event.*;public class Ingredients extends Applet {private TextField display;private double price = 7.00;public void init() {this.add(new Label("What do you want on your pizza?", Label.CENTER));Pricer p = new Pricer(this);Checkbox pepperoni = new Checkbox("Pepperoni");this.add(pepperoni);pepperoni.addItemListener(p);Checkbox olives = new Checkbox("Olives");olives.addItemListener(p);this.add(olives);Checkbox onions = new Checkbox("Onions");onions.addItemListener(p);this.add(onions);Checkbox sausage = new Checkbox("Sausage");sausage.addItemListener(p);this.add(sausage);Checkbox peppers = new Checkbox("Peppers");peppers.addItemListener(p);this.add(peppers);Checkbox extraCheese = new Checkbox("Extra Cheese");extraCheese.addItemListener(p);this.add(extraCheese);Checkbox ham = new Checkbox("Ham");ham.addItemListener(p);this.add(ham);Checkbox pineapple = new Checkbox("Pineapple");pineapple.addItemListener(p);this.add(pineapplec);Checkbox anchovies = new Checkbox("Anchovies");anchovies.addItemListener(p);this.add(anchovies);this.display = new TextField(String.valueOf(price));// so people can't change the price of the pizzadisplay.setEditable(false);this.add(display);}public void setPrice(double price) {this.price = price;display.setText(String.valueOf(price));}public double getPrice() {return this.price;}}class Pricer implements ItemListener {private Ingredients out;public Pricer(Ingredients out) {this.out = out;}public void itemStateChanged(ItemEvent ie) {double price = out.getPrice();if (ie.getStateChange() == ItemEvent.SELECTED) price += 0.50;else price -= 0.50;// Change the priceout.setPrice(price);}}java.awt.CheckboxGroup
Checkbox groups are collections of checkboxes with the special property that no more than one checkbox in the same group can be selected at a time. The checkboxes in aCheckboxGroupare often called radio buttons. Checkboxes that are members of the sameCheckboxGroupcannot be checked simultaneously. When the user checks one, all others are unchecked automatically.
The constructor for aCheckboxGroupis trivial. No arguments are needed. You do not even need to add theCheckboxGroupto the applet since checkbox groups are themselves not user-interface widgets, just ways of arranging checkboxes.
CheckboxGroup cbg = new CheckboxGroup();
To make check boxes act like radio buttons, use this constructor for eachCheckboxin the group.
public Checkbox(String label, CheckboxGroup cbg, boolean checked)
The label is the label for thisCheckbox. TheCheckboxGroupis the group you want thisCheckboxto belong to and must already exist.
At any time, you can get or set the selectedCheckboxwith these two methods:
public Checkbox getSelectedCheckbox()public void setSelectedCheckbox(Checkbox box)java.awt.CheckboxGroup example
The following program asks the customer how they're going to pay for their pizza, Visa, Mastercard, American Express, Discover, cash or check. Someone may want both anchovies and pineapple on their pizza, but they're unlikely to pay with both Visa and American Express.
![]()
import java.applet.*;import java.awt.*;public class PaymentMethod extends Applet {public void init() {this.add(new Label("How will you pay for your pizza?"));CheckboxGroup cbg = new CheckboxGroup();this.add(new Checkbox("Visa", cbg, false));this.add(new Checkbox("Mastercard", cbg, false));this.add(new Checkbox("American Express", cbg, false));this.add(new Checkbox("Discover", cbg, false));this.add(new Checkbox("Cash", cbg, true)); // the default}There isn't any action in this simple example applet. If you need to add action as radio buttons are checked and unchecked, you do it just the same as for any other}Checkbox.
java.awt.List
Scrolling lists are useful for storing long lists of things one to a line. The things in the list are called items, but each one is just a String. For example,
List Methods
You create a newListwith one of these three constructors:
public List()public List(int numLines)For example,public List(int numLines, boolean allowMultipleSelections)
List l = new List(8, true);
numLinesis the number of items you want to be visible in the scrolling list. It is not necessarily the same as the number of items in the list which is limited only by available memory.allowMultipleSelectionssays whether the user is allowed to select more than one item at once (typically by Shift-clicking).
The following methods add items at the end of the list:
public void add(String item)These two methods add items at the specified position in the list.public void addItem(String item)
public void add(String item, int index)The following methods remove items from thepublic void addItem(String item, int index)List:
public void removeAll()public void remove(String item)public void remove(int position)public void delItem(int position)These methods allow you to retrive particular items from theList:public int getItemCount()public String getItem(int index)You ran also replace a particular item:public String[] getItems()
These methods allow you to determine which item the user has selected:public void replaceItem(String newValue, int index)
public int getSelectedIndex()public int[] getSelectedIndexes()public String getSelectedItem()public String[] getSelectedItems()If a list allows multiple selections, you should use the plural forms of the above methods. You can determine whether multiple selections are allowed withpublic Object[] getSelectedObjects()isMultipleMode()and change it withsetMultipleMode().
public boolean isMultipleMode()These methods allow you to manipulate the selection:public void setMultipleMode(boolean b)
public void select(int index)public void deselect(int index)These two methods determine whether an item at a particular index is currently visible in the List box:public boolean isIndexSelected(int index)
public int getVisibleIndex()public void makeVisible(int index)List Events
Lists can fire two separate types of events. When a list item is selected or deselected, theListfires anItemEvent. However, when the user double clicks on a list item, theListfires anActionEvent. Therefore, you can register both anItemListenerto process selections and/or anActionListenerto process double clicks.
public void addItemListener(ItemListener l)public void removeItemListener(ItemListener l)public void addActionListener(ActionListener l)The action command in thepublic void removeActionListener(ActionListener l)ActionEventis the list item which was double clicked.
java.awt.Scrollbar
Lists,TextAreas, andScrollPanes come with ready made scrollbars. However if you want to scroll any other object you'll have to use ajava.awt.Scrollbar. Scrollbars have many uses. At their most basic they're used for moving the visible area. They can also be used to set a value between two numbers. Or they can be used to flip through a number of screens as in a database operation that looks at successive records.
There are three constructors:
public Scrollbar()public Scrollbar(int orientation)Thepublic Scrollbar(int orientation, int value, int visible, int min, int max)orientationargument is one of the mnemonic constants,Scrollbar.HORIZONTALorScrollbar.VERTICAL. As you expect this determines whether theScrollbaris laid out from left to right or top to bottom.
AScrollbarhas anintvalue at all times. This value will be between theminimumand themaximumvalue set by the last two arguments to the constructor. When aScrollbaris created, its value is given by thevalueargument. The default is 0.
Finallyvisiblerepresents the size of the visible portion of the scrollable area in pixels. TheScrollbaruses this when moving up or down a page.
AScrollbarfires an adjustment event when its value changes. You register an adjustment listener to catch this event. This class needs anadjustmentValueChanged()method with this signature:
public void adjustmentValueChanged(AdjustmentEvent e)
The following program is an applet that changes the number in aTextFieldbetween 1 and 100 based on the position of the thumb (the movable part of theScrollbar). In a practical application the number would of course mean something.
import java.applet.*;import java.awt.*;import java.awt.event.*;public class Scrollie extends Applet implements AdjustmentListener {private TextField t;private Scrollbar sb;public void init() {int initialValue = 1;sb = new Scrollbar(Scrollbar.HORIZONTAL, initialValue, 100, 1, 100);sb.addAdjustmentListener(this);this.add(sb);this.t = new TextField(4);this.t.setText(String.valueOf(initialValue));this.add(t);}public void adjustmentValueChanged(AdjustmentEvent e)int val = sb.getValue();this.t.setText(String.valueOf(val));}}Peer vs. Swing Components
I'm not going to talk much about Swing in this course, but most of what I teach you about the standard AWT components carries over to their Swing equivalents with only trivial changes. For example, here's yet another way to write an applet that says "Cub Scouts!" in 24 point, SansSerif, bold and blue and with a yellow background.
import java.awt.*;import javax.swing.*;public class SwingCubScout extends JApplet {public void init() {JLabel cubScouts = new JLabel("Cub Scouts!");cubScouts.setForeground(Color.blue);cubScouts.setBackground(Color.yellow);cubScouts.setFont(new Font("Sans", Font.BOLD, 24));this.getContentPane().add(cubScouts);}This is almost identical to the AWT-based Cub Scout applet, except that I've imported the}javax.swingpackage and changedLabeltoJLabelandApplettoJApplet.
Week 6 Exercises
- Write an applet that with a 60 column by 10 row text area that allows the user to type some text. Add a button to this applet that clears the text area when it's pressed.
Don't worry excessively about making the applet look good. Before you can do that you'll need to learn about layout managers.
- Rewrite the payroll problem from week 2 as an applet. Provide a text field for the number of hours, a text field for the pay rate, and a non-editable text field for the output. Also provide labels to identify all three text fields and a button to calculate the result.
Don't worry about minimum wage, number of hours in the week, or other error conditions we checked before. In the event the user enters data that cannot be interpreted as a number, don't put anything in the output text field. In a couple of weeks, you'll learn how to bring up an error dialog to handle these conditions.Don't worry excessively about making the applet look good. Before you can do that you'll need to learn about layout managers. We'll cover them next weekGetting into more fun Graphicsimport java.awt.*;import java.awt.event.*;import javax.swing.*;public class ShowColors2 extends JFrame {private JButton changeColorButton;private Color color = Color.LIGHT_GRAY;private Container container;// set up GUIpublic ShowColors2(){super( "Using JColorChooser" );container = getContentPane();container.setLayout( new FlowLayout() );// set up changeColorButton and register its event handlerchangeColorButton = new JButton( "Change Color" );changeColorButton.addActionListener(new ActionListener() { // anonymous inner class// display JColorChooser when user clicks buttonpublic void actionPerformed( ActionEvent event ){color = JColorChooser.showDialog(ShowColors2.this, "Choose a color", color );// set default color, if no color is returnedif ( color == null )color = Color.LIGHT_GRAY;// change content pane's background colorcontainer.setBackground( color );}} // end anonymous inner class); // end call to addActionListenercontainer.add( changeColorButton );setSize( 400, 130 );setVisible( true );} // end ShowColor2 constructor// execute applicationpublic static void main( String args[] ){ShowColors2 application = new ShowColors2();application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );}}import java.awt.*;import java.awt.geom.*;import javax.swing.*;public class Shapes2 extends JFrame {// set window's title bar String, background color and dimensionspublic Shapes2(){super( "Drawing 2D Shapes" );getContentPane().setBackground( Color.WHITE );setSize( 400, 400 );setVisible( true );}// draw general pathspublic void paint( Graphics g ){super.paint( g ); // call superclass's paint methodint xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };Graphics2D g2d = ( Graphics2D ) g;GeneralPath star = new GeneralPath(); // create GeneralPath object// set the initial coordinate of the General Pathstar.moveTo( xPoints[ 0 ], yPoints[ 0 ] );// create the star--this does not draw the starfor ( int count = 1; count < xPoints.length; count++ )star.lineTo( xPoints[ count ], yPoints[ count ] );star.closePath(); // close the shapeg2d.translate( 200, 200 ); // translate the origin to (200, 200)// rotate around origin and draw stars in random colorsfor ( int count = 1; count <= 20; count++ ) {g2d.rotate( Math.PI / 10.0 ); // rotate coordinate system// set random drawing colorg2d.setColor( new Color( ( int ) ( Math.random() * 256 ),( int ) ( Math.random() * 256 ),( int ) ( Math.random() * 256 ) ) );g2d.fill( star ); // draw filled star}} // end method paint// execute applicationpublic static void main( String args[] ){Shapes2 application = new Shapes2();application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );}}
An example of text fields in Java
The following applet reads text from oneTextFieldand capitalizes it in anotherTextField.
![]()
import java.applet.*;import java.awt.*;import java.awt.event.*;public class CapitalizeApplet extends Applet {private TextField input;private TextField output;public void init () {// Construct the TextFieldsthis.input = new TextField(40);this.output = new TextField(40);this.output.setEditable(false);Button b = new Button("Capitalize");// add the button to the layoutthis.add(input);this.add(b);this.add(output);// specify that action events sent by the// button or the input TextField should be handled// by the same CapitalizerAction objectCapitalizerAction ca = new CapitalizerAction(input, output);b.addActionListener(ca);this.input.addActionListener(ca);// notice that ActionEvents produced by output are ignored.}}class CapitalizerAction implements ActionListener {private TextField in;private TextField out;public CapitalizerAction(TextField in, TextField out) {this.in = in;this.out = out;}public void actionPerformed(ActionEvent ae) {String s = in.getText();out.setText(s.toUpperCase());}In this program, a different pattern is used for handling events. The constructor for the}CapitalizerActionclass is used to pass in references to the different components theactionPerformed()method affects.
An example of text fields in Java
An alternate pattern uses an inner class so the private fields can be accessed directly.
import java.applet.*;import java.awt.*;import java.awt.event.*;public class CapitalizeApplet extends Applet {private TextField input;private TextField output;public void init () {// Construct the TextFieldsthis.input = new TextField(40);this.output = new TextField(40);this.output.setEditable(false);Button b = new Button("Capitalize");// add the button to the layoutthis.add(input);this.add(b);this.add(output);// specify that action events sent by the// button or the input TextField should be handled// by the same CapitalizerAction objectCapitalizerAction ca = new CapitalizerAction();b.addActionListener(ca);this.input.addActionListener(ca);// notice that ActionEvents produced by output are ignored.}class CapitalizerAction implements ActionListener {public void actionPerformed(ActionEvent ae) {String s = input.getText();output.setText(s.toUpperCase());}}}TextArea
Thejava.awt.TextAreaclass is a subclass ofjava.awt.TextComponentthat provides a widget for editing multiple lines of text. It's useful for input and output.
There are five constructors:
public TextArea()public TextArea(String text)public TextArea(int rows, int columns)public TextArea(String text, int rows, int columns)Because of the way Java lays out components, you should not use the noargs constructor. Either start off with apublic TextArea(String text, int rows, int columns, int scrollbars)Stringor specify the number of rows and columns this area is expected to hold. For example,
By default, TextAreas don't have scrollbars. However you can add them by passing one of these constants to the constructor:TextArea address = new TextArea("Type your address here", 5, 80);
TextArea.SCROLLBARS_BOTHTextArea.SCROLLBARS_HORIZONTAL_ONLYTextArea.SCROLLBARS_NONEFor example,TextArea.SCROLLBARS_VERTICAL_ONLY
TextArea instructions =Unlike text fields, text areas do not generate action events when the user hits return inside the area. Instead, the line is broken and the caret moves on to the next row.new TextArea("", 15, 70, TextArea.SCROLLBARS_VERTICAL_ONLY);
However, thegetText()method does return the contents of theTextArea, and thesetText()method does change it. ThesetEditable()method lets you determine whether or not, the user can modify the contents of aTextField. If these methods sound familiar it's because they're both inherited from the common superclass ofTextFieldandTextArea,TextComponent.
Furthermore, you can append text to aTextAreawith theappend()method, insert text into the middle of aTextAreawith theinsert()method, and replace a block of text with thereplaceRange()method:
public void insert(String text, int position)public void append(String text)public void replaceRange(String text, int start, int end)TextComponent
BothTextAreaandTextFieldare subclasses ofjava.awt.TextComponent. This class contains methods common to both classes including several you've already seen:getText(),setText(), andsetEditable(). TheTextComponentclass also defines methods for manipulating the selection and the caret and for processingTextEvents.
The selection is used for copy and paste and other purposes. The first character in aTextComponentis character 0; the second is character 1, and so on.
public int getSelectionStart()public void setSelectionStart(int selectionStart)public int getSelectionEnd()public void setSelectionEnd(int selectionEnd)public void select(int selectionStart, int selectionEnd)public void selectAll()The caret is the insertion point. It's where text appears when the user types. There are two methods to adjust it:public String getSelectedText()
public void setCaretPosition(int position)public int getCaretPosition()TextEvents
BothTextAreaandTextFieldcan install aTextListenerthat catchesTextEvents.TextComponents fireTextEvents every time the text of the component changes. This is more or less every time the user hits a key in the component.
Thejava.awt.event.TextListenerinterface defines a single method,textValueChanged():
You register apublic void textValueChanged(TextEvent te)TextListenerwith aTextComponentby calling the component'saddTextListener()method. For example,
TextArea password = new TextArea(24)However, most of the time it's sufficient to just get and set the text as you need it. It's really quite rare that you need to process it character by character.password.addTextListener(new PasswordChecker());
ATextListenercan be removed by callingremoveTextListener().
public void removeTextListener(TextListener tl)
java.awt.Canvas
Thejava.awt.Canvasclass is a rectangular area on which you can draw using the methods ofjava.awt.Graphicsdiscussed last week. TheCanvasclass has only three methods:
public Canvas()public void addNotify()You generally won't instantiate a canvas directly. Instead you'll subclass it and override thepublic void paint(Graphics g)paint()method in your subclass to draw the picture you want.
For example the followingCanvasdraws a big red oval you can add to your applet.
import java.awt.*;public class RedOval extends Canvas {public void paint(Graphics g) {Dimension d = this.getSize();g.setColor(Color.red);g.fillOval(0, 0, d.width, d.height);}public Dimension getMinimumSize() {return new Dimension(50, 100);}public Dimension getPreferredSize() {return new Dimension(150, 300);}public Dimension getMaximumSize() {return new Dimension(200, 400);}Any applet that uses components should not also override}paint(). Doing so will have unexpected effects because of the way Java arranges components. Instead, create aCanvasobject and do your drawing in itspaint()method.
Custom canvases are added to applets just like any other component. For example,
public void init() {this.add(new RedOval());Canvases themselves do not normally fire any events. Next week, we'll see how to change that in the subclasses.}
An alternate approach
import java.awt.*;public class ColoredOval extends Canvas {public ColoredOval() {this(Color.RED, 100, 100);}public ColoredOval(Color c) {this(c, 100, 100);}public ColoredOval(int width, int height) {this(Color.RED, width, height);}public ColoredOval(Color c, int width, int height) {this.setColor(c);this.setSize(width, height);}public void paint(Graphics g) {Dimension d = this.getSize();g.fillOval(0, 0, d.width, d.height);}This is almost but not quite the same effect as the previous applet. (It's a little less resizeable.)}
java.awt.Choice
Thejava.awt.Choiceclass implements a popup menu with a fixed position. (Thejava.awt.PopupMenuclass is a popup menu with no fixed position. It pops up when the user clicks
and holds the right mouse button.)
Creating a choice menu is a little more complex than creating the other user interface components you've seen. There's an extra step, adding the menu items to the menu. That is the five steps are
For example
- Declare the
Choice- Allocate the
Choice- Add the menu items to the
Choice- Add the
Choiceto thelayout- Add an
ItemListenerto theChoice
public void init() {Choice ch;ch = new Choice();ch.addItem("1");ch.addItem("2");ch.addItem("3");ch.addItem("4");ch.addItem("5");add(ch);}Methods of java.awt.Choice
TheChoiceclass has a number of methods to add, remove, and return different items from the list. The list starts counting at 0.
public int getItemCount()public String getItem(int index)public void add(String item)public void addItem(String item)public void insert(String item, int position)public void remove(String item)public void remove(int position)However, most of the item you'll just build thepublic void removeAll()Choicewhen the applet starts up, and not modify it later.
These methods get or set the current selected item in theChoice, that is the item that's shown.
public void removeAll()public String getSelectedItem()public Object[] getSelectedObjects()public int getSelectedIndex()public void select(int position)public void select(String item)ItemListeners
When the user changes the selected item in aChoice, theChoicefires twoItemListenerevents, one to indicate that the original selection has been deselected and the other to indicate that a new selection has been made. You can process these events by registering anItemListenerobject with yourChoice.
You do not always need to do this. It is not uncommon to only check the value of aChoicewhen some other event occurs like aButtonpress.
For example, the following applet builds aChoicemenu with the numbers from 1 to 5. When the user makes a selection, the applet beeps that many times.
import java.applet.*;import java.awt.*;import java.awt.event.*;public class MultiBeep extends Applet {public void init() {Choice ch;ch = new Choice();ch.addItem("1");ch.addItem("2");ch.addItem("3");ch.addItem("4");ch.addItem("5");this.add(ch);ch.addItemListener(new BeepItem());}}class BeepItem implements ItemListener {public void itemStateChanged(ItemEvent ie) {if (ie.getStateChange() == ItemEvent.SELECTED) {String name = (String) ie.getItem();Toolkit tk = Toolkit.getDefaultToolkit();try {int n = Integer.parseInt(name);for (int i = 0; i < n; i++) tk.beep();}catch (Exception e) {tk.beep();}}}}TheBeepItemclass implements theItemListenerinterface. It filters out events caused by items being deselected withItemEvent.getStateChange()and only beeps if an item was selected. The available convenience constants you can check are:ItemEvent.DESELECTEDItemEvent.ITEM_FIRSTItemEvent.ITEM_LASTItemEvent.ITEM_STATE_CHANGEDItemEvent.SELECTEDTheItemEvent.getItem()method is used to retrieve the actual selected item.java.awt.Checkbox
Check boxes are used to select abooleanvalue. EachCheckboxhas a label that should be used to tell the user what theCheckboxrepresents. For instance aCheckboxwith the label "Anchovies" would be checked if the user wants anchovies on their pizza and unchecked if they don't.
Checkboxes are often used to select from a list of possible choices when as few selections as zero or as many as everything on the list may be made. Adding aCheckboxto an applet is simple. Just declare it, construct it and add it.
Checkbox c c = new Checkbox("Pepperoni"));As usual these steps may be combined into the single lineadd(c);
add(new Checkbox("Pepperoni"));
By default check boxes are unchecked when created. If you want aCheckboxto start life checked, use the following constructor instead:
add(new Checkbox("Pepperoni", null, true));
Thenullis a reference to aCheckboxGroup. Passingnullfor this argument says that thisCheckboxdoes not belong to aCheckboxGroup.
EveryCheckboxhas abooleanvalue, eithertrueorfalse. When theCheckboxis checked that value istrue. When it is unchecked that value is false. You access this value using theCheckbox'sgetState()andsetState(boolean b)methods. For example
private void handleCheckbox(Checkbox c) {if (c.getState()) price += 0.50;else price -= 0.50;}Checkbox Events
When the aCheckboxchanges state, normally as a result of user action, it fires anItemEvent. Most of the time you ignore this event. Instead you manually check the state of aCheckboxwhen you need to know it. However if you want to know immediately when aCheckboxchanges state, you can register anItemListenerfor theCheckbox.
AnItemEventis exactly the same as the item event fired by aChoice. In fact item events are used to indicate selections or deselections in any sort of list including checkboxes, radio buttons, choices, and lists.
For example, the following program is an applet that asks the age-old question, "What do you want on your pizza?" When an ingredient is checked the price of the pizza goes up by fifty cents. When an ingredient is unchecked fifty cents is taken off. The price is shown in aTextField.
![]()
import java.applet.*;import java.awt.*;import java.awt.event.*;public class Ingredients extends Applet {private TextField display;private double price = 7.00;public void init() {this.add(new Label("What do you want on your pizza?", Label.CENTER));Pricer p = new Pricer(this);Checkbox pepperoni = new Checkbox("Pepperoni");this.add(pepperoni);pepperoni.addItemListener(p);Checkbox olives = new Checkbox("Olives");olives.addItemListener(p);this.add(olives);Checkbox onions = new Checkbox("Onions");onions.addItemListener(p);this.add(onions);Checkbox sausage = new Checkbox("Sausage");sausage.addItemListener(p);this.add(sausage);Checkbox peppers = new Checkbox("Peppers");peppers.addItemListener(p);this.add(peppers);Checkbox extraCheese = new Checkbox("Extra Cheese");extraCheese.addItemListener(p);this.add(extraCheese);Checkbox ham = new Checkbox("Ham");ham.addItemListener(p);this.add(ham);Checkbox pineapple = new Checkbox("Pineapple");pineapple.addItemListener(p);this.add(pineapplec);Checkbox anchovies = new Checkbox("Anchovies");anchovies.addItemListener(p);this.add(anchovies);this.display = new TextField(String.valueOf(price));// so people can't change the price of the pizzadisplay.setEditable(false);this.add(display);}public void setPrice(double price) {this.price = price;display.setText(String.valueOf(price));}public double getPrice() {return this.price;}}class Pricer implements ItemListener {private Ingredients out;public Pricer(Ingredients out) {this.out = out;}public void itemStateChanged(ItemEvent ie) {double price = out.getPrice();if (ie.getStateChange() == ItemEvent.SELECTED) price += 0.50;else price -= 0.50;// Change the priceout.setPrice(price);}}java.awt.CheckboxGroup
Checkbox groups are collections of checkboxes with the special property that no more than one checkbox in the same group can be selected at a time. The checkboxes in aCheckboxGroupare often called radio buttons. Checkboxes that are members of the sameCheckboxGroupcannot be checked simultaneously. When the user checks one, all others are unchecked automatically.
The constructor for aCheckboxGroupis trivial. No arguments are needed. You do not even need to add theCheckboxGroupto the applet since checkbox groups are themselves not user-interface widgets, just ways of arranging checkboxes.
CheckboxGroup cbg = new CheckboxGroup();
To make check boxes act like radio buttons, use this constructor for eachCheckboxin the group.
public Checkbox(String label, CheckboxGroup cbg, boolean checked)
The label is the label for thisCheckbox. TheCheckboxGroupis the group you want thisCheckboxto belong to and must already exist.
At any time, you can get or set the selectedCheckboxwith these two methods:
public Checkbox getSelectedCheckbox()public void setSelectedCheckbox(Checkbox box)java.awt.CheckboxGroup example
The following program asks the customer how they're going to pay for their pizza, Visa, Mastercard, American Express, Discover, cash or check. Someone may want both anchovies and pineapple on their pizza, but they're unlikely to pay with both Visa and American Express.
![]()
import java.applet.*;import java.awt.*;public class PaymentMethod extends Applet {public void init() {this.add(new Label("How will you pay for your pizza?"));CheckboxGroup cbg = new CheckboxGroup();this.add(new Checkbox("Visa", cbg, false));this.add(new Checkbox("Mastercard", cbg, false));this.add(new Checkbox("American Express", cbg, false));this.add(new Checkbox("Discover", cbg, false));this.add(new Checkbox("Cash", cbg, true)); // the default}There isn't any action in this simple example applet. If you need to add action as radio buttons are checked and unchecked, you do it just the same as for any other}Checkbox.
java.awt.List
Scrolling lists are useful for storing long lists of things one to a line. The things in the list are called items, but each one is just a String. For example,
List Methods
You create a newListwith one of these three constructors:
public List()public List(int numLines)For example,public List(int numLines, boolean allowMultipleSelections)
List l = new List(8, true);
numLinesis the number of items you want to be visible in the scrolling list. It is not necessarily the same as the number of items in the list which is limited only by available memory.allowMultipleSelectionssays whether the user is allowed to select more than one item at once (typically by Shift-clicking).
The following methods add items at the end of the list:
public void add(String item)These two methods add items at the specified position in the list.public void addItem(String item)
public void add(String item, int index)The following methods remove items from thepublic void addItem(String item, int index)List:
public void removeAll()public void remove(String item)public void remove(int position)public void delItem(int position)These methods allow you to retrive particular items from theList:public int getItemCount()public String getItem(int index)You ran also replace a particular item:public String[] getItems()
These methods allow you to determine which item the user has selected:public void replaceItem(String newValue, int index)
public int getSelectedIndex()public int[] getSelectedIndexes()public String getSelectedItem()public String[] getSelectedItems()If a list allows multiple selections, you should use the plural forms of the above methods. You can determine whether multiple selections are allowed withpublic Object[] getSelectedObjects()isMultipleMode()and change it withsetMultipleMode().
public boolean isMultipleMode()These methods allow you to manipulate the selection:public void setMultipleMode(boolean b)
public void select(int index)public void deselect(int index)These two methods determine whether an item at a particular index is currently visible in the List box:public boolean isIndexSelected(int index)
public int getVisibleIndex()public void makeVisible(int index)List Events
Lists can fire two separate types of events. When a list item is selected or deselected, theListfires anItemEvent. However, when the user double clicks on a list item, theListfires anActionEvent. Therefore, you can register both anItemListenerto process selections and/or anActionListenerto process double clicks.
public void addItemListener(ItemListener l)public void removeItemListener(ItemListener l)public void addActionListener(ActionListener l)The action command in thepublic void removeActionListener(ActionListener l)ActionEventis the list item which was double clicked.
java.awt.Scrollbar
Lists,TextAreas, andScrollPanes come with ready made scrollbars. However if you want to scroll any other object you'll have to use ajava.awt.Scrollbar. Scrollbars have many uses. At their most basic they're used for moving the visible area. They can also be used to set a value between two numbers. Or they can be used to flip through a number of screens as in a database operation that looks at successive records.
There are three constructors:
public Scrollbar()public Scrollbar(int orientation)Thepublic Scrollbar(int orientation, int value, int visible, int min, int max)orientationargument is one of the mnemonic constants,Scrollbar.HORIZONTALorScrollbar.VERTICAL. As you expect this determines whether theScrollbaris laid out from left to right or top to bottom.
AScrollbarhas anintvalue at all times. This value will be between theminimumand themaximumvalue set by the last two arguments to the constructor. When aScrollbaris created, its value is given by thevalueargument. The default is 0.
Finallyvisiblerepresents the size of the visible portion of the scrollable area in pixels. TheScrollbaruses this when moving up or down a page.
AScrollbarfires an adjustment event when its value changes. You register an adjustment listener to catch this event. This class needs anadjustmentValueChanged()method with this signature:
public void adjustmentValueChanged(AdjustmentEvent e)
The following program is an applet that changes the number in aTextFieldbetween 1 and 100 based on the position of the thumb (the movable part of theScrollbar). In a practical application the number would of course mean something.
import java.applet.*;import java.awt.*;import java.awt.event.*;public class Scrollie extends Applet implements AdjustmentListener {private TextField t;private Scrollbar sb;public void init() {int initialValue = 1;sb = new Scrollbar(Scrollbar.HORIZONTAL, initialValue, 100, 1, 100);sb.addAdjustmentListener(this);this.add(sb);this.t = new TextField(4);this.t.setText(String.valueOf(initialValue));this.add(t);}public void adjustmentValueChanged(AdjustmentEvent e)int val = sb.getValue();this.t.setText(String.valueOf(val));}}Peer vs. Swing Components
I'm not going to talk much about Swing in this course, but most of what I teach you about the standard AWT components carries over to their Swing equivalents with only trivial changes. For example, here's yet another way to write an applet that says "Cub Scouts!" in 24 point, SansSerif, bold and blue and with a yellow background.
import java.awt.*;import javax.swing.*;public class SwingCubScout extends JApplet {public void init() {JLabel cubScouts = new JLabel("Cub Scouts!");cubScouts.setForeground(Color.blue);cubScouts.setBackground(Color.yellow);cubScouts.setFont(new Font("Sans", Font.BOLD, 24));this.getContentPane().add(cubScouts);}This is almost identical to the AWT-based Cub Scout applet, except that I've imported the}javax.swingpackage and changedLabeltoJLabelandApplettoJApplet.
Week 6 Exercises
- Write an applet that with a 60 column by 10 row text area that allows the user to type some text. Add a button to this applet that clears the text area when it's pressed.
Don't worry excessively about making the applet look good. Before you can do that you'll need to learn about layout managers.
- Rewrite the payroll problem from week 2 as an applet. Provide a text field for the number of hours, a text field for the pay rate, and a non-editable text field for the output. Also provide labels to identify all three text fields and a button to calculate the result.
Don't worry about minimum wage, number of hours in the week, or other error conditions we checked before. In the event the user enters data that cannot be interpreted as a number, don't put anything in the output text field. In a couple of weeks, you'll learn how to bring up an error dialog to handle these conditions.Don't worry excessively about making the applet look good. Before you can do that you'll need to learn about layout managers. We'll cover them next weekGetting into more fun Graphicsimport java.awt.*;import java.awt.event.*;import javax.swing.*;public class ShowColors2 extends JFrame {private JButton changeColorButton;private Color color = Color.LIGHT_GRAY;private Container container;// set up GUIpublic ShowColors2(){super( "Using JColorChooser" );container = getContentPane();container.setLayout( new FlowLayout() );// set up changeColorButton and register its event handlerchangeColorButton = new JButton( "Change Color" );changeColorButton.addActionListener(new ActionListener() { // anonymous inner class// display JColorChooser when user clicks buttonpublic void actionPerformed( ActionEvent event ){color = JColorChooser.showDialog(ShowColors2.this, "Choose a color", color );// set default color, if no color is returnedif ( color == null )color = Color.LIGHT_GRAY;// change content pane's background colorcontainer.setBackground( color );}} // end anonymous inner class); // end call to addActionListenercontainer.add( changeColorButton );setSize( 400, 130 );setVisible( true );} // end ShowColor2 constructor// execute applicationpublic static void main( String args[] ){ShowColors2 application = new ShowColors2();application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );}}import java.awt.*;import java.awt.geom.*;import javax.swing.*;public class Shapes2 extends JFrame {// set window's title bar String, background color and dimensionspublic Shapes2(){super( "Drawing 2D Shapes" );getContentPane().setBackground( Color.WHITE );setSize( 400, 400 );setVisible( true );}// draw general pathspublic void paint( Graphics g ){super.paint( g ); // call superclass's paint methodint xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };Graphics2D g2d = ( Graphics2D ) g;GeneralPath star = new GeneralPath(); // create GeneralPath object// set the initial coordinate of the General Pathstar.moveTo( xPoints[ 0 ], yPoints[ 0 ] );// create the star--this does not draw the starfor ( int count = 1; count < xPoints.length; count++ )star.lineTo( xPoints[ count ], yPoints[ count ] );star.closePath(); // close the shapeg2d.translate( 200, 200 ); // translate the origin to (200, 200)// rotate around origin and draw stars in random colorsfor ( int count = 1; count <= 20; count++ ) {g2d.rotate( Math.PI / 10.0 ); // rotate coordinate system// set random drawing colorg2d.setColor( new Color( ( int ) ( Math.random() * 256 ),( int ) ( Math.random() * 256 ),( int ) ( Math.random() * 256 ) ) );g2d.fill( star ); // draw filled star}} // end method paint// execute applicationpublic static void main( String args[] ){Shapes2 application = new Shapes2();application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );}}
No comments:
Post a Comment