|
|
|
1000 Java Tips ebook
|
|
 

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java
programming articles and tips. Please take your copy here.
Take your copy of free "Java Technology Screensaver"!. |
|
The Java Lesson 31: Choice, List, and Checkbox controls
|
JavaFAQ Home » Java Lessons by Jon Huhtala

Java Lesson 31:
Choice,
List, and Checkbox controls
The Choice
class
-
Implementing the ItemListener interface
-
Registering an ItemListener by calling the
choice's addItemListener() method
-
Coding an itemStateChanged() method within the registered
ItemListener that
defines the processing to be performed
When the user selects an item within the choice menu, an ItemEvent will be fired to the
itemStateChanged() method
of the registered ItemListener for processing.
Choice parts = new Choice();
will create an empty choice
menu. To add items to a choice menu, call its add() method passing it a string representing the
text of the item to be added. For example,
parts.add("Framistan"); parts.add("Whatsit"); parts.add("Widget");
will add three items to the
parts choice menu. By
default, the first item added to the choice menu will be the current item and
the preferred column size of the choice menu is determined by the size of its
largest item (depending upon the layout manager).
|
Method |
Usage |
|
add() |
Adds an item to this choice
menu |
|
addItem() |
Adds an item to this choice
menu. This is an older version of the add() method but is not yet
deprecated. |
|
addItemListener() |
Adds the specified ItemListener to receive
ItemEvent objects
from this choice menu |
|
getItem() |
Gets the string at the
specified index in this choice menu |
|
getItemCount() |
Gets the number of items in
this choice menu |
|
getSelectedIndex() |
Gets the index of the currently selected
item |
|
getSelectedItem() |
Gets the string representation of the
currently selected item |
|
insert() |
Inserts an item into this choice menu at
the specified position |
|
remove() |
Removes an item from this choice menu
(overloaded) |
|
removeItemListener() |
Removes the specified ItemListener so it no
longer receives ItemEvent objects from this choice menu |
|
select() |
Selects the specified item within this
choice menu
(overloaded) |
Consult the help facility of your Java development environment or the Java
API for more details.
Example:
import
java.awt.*; import java.awt.event.*;
public class App extends
Frame implements WindowListener, ItemListener {
Choice
itemChoice; Label price; String[] items = {"Apples",
"Bananas", "Grapes", "Oranges"}; double[] prices = {1.19, .79,
.99, 1.49};
public static void main(String[] args)
{ App myWindow = new App("Fruit market using
Choice"); myWindow.setSize(400,
100); myWindow.setVisible(true);
}
public App(String title) {
super(title);
addWindowListener(this); setLayout(new
FlowLayout()); add(new Label("Fruit
selection")); itemChoice = new
Choice(); for (int i=0; i < items.length; i++)
{
itemChoice.add(items[i]); }
add(itemChoice);
itemChoice.addItemListener(this); price = new
Label("Select one of the " +
itemChoice.getItemCount() + " listed fruits to see its
price"); price.setFont(new Font("SanSerif", Font.BOLD
+ Font.ITALIC, 16));
price.setForeground(Color.red);
price.setAlignment(Label.CENTER);
add(price); }
public void itemStateChanged(ItemEvent
e) { price.setText(itemChoice.getSelectedItem() + "
are " +
prices[itemChoice.getSelectedIndex()] + " per pound");
}
public void windowClosing(WindowEvent e)
{ dispose();
System.exit(0); }
public void
windowOpened(WindowEvent e) {} public void
windowActivated(WindowEvent e) {} public void
windowIconified(WindowEvent e) {} public void
windowDeiconified(WindowEvent e) {} public void
windowDeactivated(WindowEvent e) {} public void
windowClosed(WindowEvent e) {} }
Notes:
-
In order to become a
registered ItemListener, the class implements the ItemListener
interface
-
The application class has
instance variables for referencing the choice menu (itemChoice), an item price label (price), an array of item
names (items), and an
array of corresponding item prices (prices)
-
The choice menu is
instantiated and populated in the class constructor. The for loop adds each item name
(from the array of item names) as an item in the choice menu. The choice
menu is then added to the application frame and its ItemListener registered.
-
Near the end of the class
constructor, the price
label is instantiated and added to the frame It initially displays the
number of items available in the choice menu and prompts the user to choose
one.
-
The itemStateChanged() method is required by the
ItemListener interface.
It is automatically called when the user selects an item within the choice
menu and receives an ItemEvent object as a parameter. In this sample, only one
action will trigger this event so the ItemEvent object isn't tested or used. The method simply
displays the name of the item the user selected and its price per
pound.
The List class
-
Presents the user with a
scrolling list of text items. The list can be set up so that the user can
choose either one item or multiple items. Clicking on an item that isn't
selected selects it. Clicking on an item that is already selected deselects
it. If the list only allows a single selection, selecting an item causes any
other selected item to be automatically deselected.
-
Can fire both ActionEvent objects and ItemEvent objects. When an item is selected or deselected, an
instance of ItemEvent is
sent to the list's registered ItemListener for processing by its itemStateChanged() method. When the user
double-clicks on an item in the list or presses the RETURN key while an item is selected, an instance of ActionEvent is sent to the
list's registered ActionListener for processing by its actionPerformed() method.
List parts = new List( ;
will create an empty list
capable of displaying 8 items without scrolling and only permitting a single
selection. To create an empty list capable of displaying 5 items without
scrolling and permitting multiple selections, one could code
List parts = new List(5, true);
To add items to a list, call
its add() method passing
it a string representing the text of the item to be added. For example,
parts.add("Framistan"); parts.add("Whatsit"); parts.add("Widget");
will add three items to the
parts list. By default,
the items will appear in the list in the order they are added and none will be
initially selected.
|
Method |
Usage |
|
add() |
Adds an item to this list
(overloaded) |
|
addActionListener() |
Adds the specified ActionListener to
receive ActionEvent objects from this list |
|
addItemListener() |
Adds the specified ItemListener to receive
ItemEvent objects
from this list |
|
deSelect() |
Deselects the specified item within this
list |
|
getItem() |
Gets the string at the
specified index in this list |
|
getItemCount() |
Gets the number of items in
this list |
|
getItems() |
Gets an array of strings
representing all items in this list |
|
getSelectedIndex() |
Gets the index of the currently selected
item |
|
getSelectedIndexes() |
Gets an array of indexes for all currently
selected items |
|
getSelectedItem() |
Gets the string representation of the
currently selected item |
|
getSelectedItems() |
Gets an array of strings representing all
currently selected items |
|
isMultipleMode() |
Determines whether this list allows
multiple selections |
|
remove() |
Removes an item from this list
(overloaded) |
|
removeActionListener() |
Removes the specified ActionListener so it no
longer receives ActionEvent objects from this list |
|
removeAll() |
Removes all items from this list |
|
removeItemListener() |
Removes the specified ItemListener so it no
longer receives ItemEvent objects from this list |
|
replaceItem() |
Replaces a specified item within the
list |
|
select() |
Selects the specified item within this
list |
|
setMultipleMode() |
Sets the flag that determines whether this
list allows multiple
selections |
Consult the help facility of your Java development environment or the Java
API for more details.
Example:
import
java.awt.*; import java.awt.event.*;
public class App extends
Frame implements WindowListener, ItemListener {
List
itemList; TextArea priceInfo; String[] items =
{"Apples", "Bananas", "Grapes", "Oranges"}; double[] prices =
{1.19, .79, .99, 1.49};
public static void main(String[] args)
{ App myWindow = new App("Fruit market using
List"); myWindow.setSize(300,
200); myWindow.setVisible(true);
}
public App(String title) {
super(title);
addWindowListener(this); setLayout(new
FlowLayout());
setBackground(Color.lightGray); add(new Label("Fruit
selection")); itemList = new List(4,
true); for (int i=0; i < items.length; i++)
{
itemList.add(items[i]); }
add(itemList);
itemList.addItemListener(this); priceInfo = new
TextArea("", 4, 30, TextArea.SCROLLBARS_NONE);
priceInfo.setText("Select one or more of the "
+ itemList.getItemCount() + " listed
fruits to see the price"); priceInfo.setFont(new
Font("SanSerif", Font.PLAIN, 12));
priceInfo.setEditable(false);
add(priceInfo); }
public void
itemStateChanged(ItemEvent e) { if
(itemList.getSelectedIndexes().length == 0)
{ priceInfo.setText("You must select at
least one item"); } else
{ StringBuffer temp = new
StringBuffer(""); int[] selections =
itemList.getSelectedIndexes(); for (int i
= 0; i < selections.length; i++)
{
temp.append(itemList.getItem(selections[i]) + " are "
+
prices[selections[i]] + " per pound
");
}
priceInfo.setText(temp.toString()); }
}
public void windowClosing(WindowEvent e)
{ dispose();
System.exit(0); }
public void
windowOpened(WindowEvent e) {} public void
windowActivated(WindowEvent e) {} public void
windowIconified(WindowEvent e) {} public void
windowDeiconified(WindowEvent e) {} public void
windowDeactivated(WindowEvent e) {} public void
windowClosed(WindowEvent e) {} }
Notes:
-
In order to become a
registered ItemListener, the class implements the ItemListener
interface
-
The application class has
instance variables for referencing the list (itemList), an item price text area (priceInfo), an array of item
names (items), and an
array of corresponding item prices (prices)
-
In the class constructor, the
list is instantiated to display up to 4 items without scrolling and to allow
multiple selections. It is then populated by the for loop which adds each item name (from the
array of item names) as an item in the list. The list is then added to the
application frame and its ItemListener registered.
-
Near the end of the class
constructor, the priceInfo text area is instantiated and added to the
frame It initially displays the number of items available in the list
and prompts the user to choose one or more.
-
The itemStateChanged() method is required by the
ItemListener interface.
It is automatically called when the user selects or deselects an item within
the list and receives an ItemEvent object as a parameter. In this sample, only one
action will trigger this event so the ItemEvent object isn't tested or used. If no items are
currently selected, the method displays a message advising the user to do
so. Otherwise, it builds a multi-line message that shows the item name and
price per pound of each selected item and sets it in the text area.
-
When testing this sample, see
what happens when the list constructor is modified to allow only a single
item to be selected. Just change the second parameter in the constructor
call from true to false or omit it
entirely.
The Checkbox class
|
Object |
|
|
|
|
|
|
|
Component |
|
|
|
|
|
|
Checkbox |
-
Is used to create a graphical
component that can be in either an "on" (true) or "off" (false) state. Clicking on a check box changes its
state from "on" to "off," or from "off" to "on."
-
Can fire ItemEvent objects. When a checkbox is selected or
deselected, an instance of ItemEvent is sent to the checkbox's registered ItemListener for processing by
its itemStateChanged()
method.
-
Can be added to a CheckBoxGroup object. When so
grouped, exactly one checkbox can be in the "on" state at any given time. If a
checkbox is "on" when the user selects another checkbox within the group, it
will be set to "off" and the newly selected checkbox will be set to "on". On
most platforms, round, radio-style buttons are used to differentiate grouped
checkbox objects from ungrouped checkbox objects (that have a square button).
Checkbox mi = new Checkbox("Michigan
resident");
will create a checkbox with the
label "Michigan resident" that will be
initially "off". If you had wanted the checkbox to be initially "on", you
could have coded
Checkbox mi = new Checkbox("Michigan resident",
true);
Other constructors allow a
checkbox to be added to a group of related checkboxes. For example,
CheckboxGroup residency = new
CheckboxGroup(); Checkbox mi = new Checkbox("Michigan resident",
residency, false); Checkbox ny = new Checkbox("New York resident",
residency, true); Checkbox oh = new Checkbox("Ohio resident", residency,
false); Checkbox pa = new Checkbox("Pennsylvania resident", residency,
false);
Creates a CheckboxGroup object named
residency and four Checkbox objects named mi, ny, oh, and pa
that are part of the group. The ny checkbox is initially "on".
|
Method |
Usage |
|
addItemListener() |
Adds the specified ItemListener to receive
ItemEvent objects
from this checkbox |
|
getCheckboxGroup() |
Gets the checkbox group of this
checkbox |
|
getLabel() |
Gets the label of this checkbox |
|
getState() |
Determines if this checkbox is
in the "on" or "off" state |
|
removeItemListener() |
Removes the specified ItemListener so it no
longer receives ItemEvent objects from this checkbox |
|
setCheckboxGroup() |
Sets the checkbox group of this
checkbox |
|
setLabel() |
Sets the label of this checkbox |
|
setState() |
Sets the state of this checkbox to either
"on" or "off" |
Consult the help facility of your Java development environment or the Java
API for more details.
Example:
import
java.awt.*; import java.awt.event.*;
public class App extends
Frame implements WindowListener, ItemListener {
Panel
itemPanel; Checkbox[] itemBoxes; TextArea
priceInfo; String[] items = {"Apples", "Bananas", "Grapes",
"Oranges"}; double[] prices = {1.19, .79, .99,
1.49};
public static void main(String[] args)
{ App myWindow = new App("Fruit
market"); myWindow.setSize(300,
200); myWindow.setVisible(true);
}
public App(String title) {
super(title);
addWindowListener(this); setLayout(new
FlowLayout());
setBackground(Color.lightGray); add(new Label("Fruit
selection")); itemPanel = new
Panel(); itemPanel.setLayout(new
GridLayout(2,2)); itemBoxes = new
Checkbox[items.length]; for (int i=0; i <
items.length; i++) { itemBoxes[i] = new
Checkbox(items[i]);
itemBoxes[i].addItemListener(this);
itemPanel.add(itemBoxes[i]); }
add(itemPanel); priceInfo = new TextArea("", 4, 30,
TextArea.SCROLLBARS_NONE); priceInfo.setText("Select
one or more of the " + itemBoxes.length +
" listed fruits to see the price");
priceInfo.setFont(new Font("SanSerif", Font.PLAIN,
12));
priceInfo.setEditable(false);
add(priceInfo); }
public void
itemStateChanged(ItemEvent e) { StringBuffer temp =
new StringBuffer(""); for (int i = 0; i <
itemBoxes.length; i++) { if
(itemBoxes[i].getState() == true)
{
temp.append(itemBoxes[i].getLabel() + " are "
+ prices[i] + "
per pound
"); }
} if (temp.length() == 0)
{ temp.append("No items are
selected"); }
priceInfo.setText(temp.toString()); }
public void
windowClosing(WindowEvent e) {
dispose(); System.exit(0); }
public void windowOpened(WindowEvent e) {} public void
windowActivated(WindowEvent e) {} public void
windowIconified(WindowEvent e) {} public void
windowDeiconified(WindowEvent e) {} public void
windowDeactivated(WindowEvent e) {} public void
windowClosed(WindowEvent e) {} }
Notes:
-
In order to become a
registered ItemListener, the class implements the ItemListener
interface
-
The application class has
instance variables for referencing a panel to display a checkbox for each
item (itemPanel), an
array to reference the checkbox for each item (itemBoxes), an item price text area (priceInfo), an array of item
names (items), and an
array of corresponding item prices (prices)
-
In the class constructor, the
itemPanel is
constructed and given a GridLayout. The itemBoxes array is then instantiated to hold a reference for
each checkbox (one per item). The for loop constructs each item's Checkbox object, registers its ItemListener, and adds it to
the itemPanel. The
itemPanel is then added
to the application frame.
-
Near the end of the class
constructor, the price
text area is instantiated and added to the frame It initially displays
the number of items available for selection and prompts the user to choose
one or more.
-
The itemStateChanged() method is required by the
ItemListener interface.
It is automatically called when the user selects or deselects an item's
checkbox and receives an ItemEvent object as a parameter. In this sample, only one
action will trigger this event so the ItemEvent object isn't tested or used. An empty StringBuffer object (temp) is constructed to which
item pricing information may be appended. The for loop tests the state of each item's checkbox
and, if "on", appends the item's name and price to temp. If the loop ends with no values being
appended, it means no items are currently selected and a message is
constructed advising the user to do so. The method ends by setting the
string value of temp in
the priceInfo text
area.
-
To see how the use of a
checkbox group affects this sample, insert the statement
CheckboxGroup itemGroup = new
CheckboxGroup();
immediately in front of the
for loop within the
application's constructor method and the statement
itemBoxes[i].setCheckboxGroup(itemGroup);
inside the for loop immediately after
the construction of the Checkbox object.
Lab exercise for Ferris
students
E-mail your answers to this
assignment no later than
the due date listed in the class schedule.
Review questions
-
Which statements are true of
a Choice object? (choose two)
-
it may fire an ActionEvent
-
it never allows more than
one item to be selected at the same time
-
it inherits the features
of the Component class
-
it may be grouped with
other Choice objects in a ChoiceGroup
-
its event handling is
defined within the itemChanged()
method of its registered ItemListener
-
Assuming that all unseen
code is correct, what will result from attempting to compile and execute the
following statement?
List myList = new List(6);
-
a compile error
-
a runtime error
-
a List object that can never contain more than 6 items in its
menu
-
a List object that will permit more than one item to be selected
at the same time
-
none of the above
-
Which of the following
expressions can be used to determine the number of items currently selected
within a List object named myList? (choose two)
-
myList.getItemCount()
-
myList.getSelectedItemCount()
-
myList.getSelectedIndexes().length
-
myList.getSelectedItems().length
-
myList.getItems().length
-
Assume that hourly and salaried are Checkbox
objects in the same checkbox group and each has properly registered the same
ItemListener whose event handler is
shown by the following code. Based on this code, what will result from the
user clicking the hourly checkbox when
the salaried checkbox is currently
"on"? Assume that all unseen code is correct and that line numbers are for
reference purposes only.
1 2 3 |
public
void itemStateChanged(ItemEvent e) {
salaried.setState(hourly.getState()); } |
-
a compile error will occur
at line 2
-
the salaried checkbox will be "on" and the
hourly checkbox will be "off"
-
the salaried checkbox will be "off" and the
hourly checkbox will be "on"
-
both the salaried and hourly checkboxes will be "on"
-
both the salaried and hourly checkboxes will be "off" Printer Friendly Page
Send to a Friend
..
Search here again if you need more info!
|
|
|