Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

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 Go to all tips in Java Lessons by Jon Huhtala


Bookmark and Share
All Java Lessons contents page | Java Lesson 1 | Java Lesson 2 | Java Lesson 3 | Java Lesson 4 | Java Lesson 5 | Java Lesson 6 | Java Lesson 7 | Java Lesson 8 | Java Lesson 9 | Java Lesson 10 | Java Lesson 11 | Java Lesson 12 | Java Lesson 13 | Java Lesson 14 | Java Lesson 15 | Java Lesson 16 | Java Lesson 17 | Java Lesson 18 | Java Lesson 19 | Java Lesson 20 | Java Lesson 21 | Java Lesson 22 | Java Lesson 23 | Java Lesson 24 | Java Lesson 25 | Java Lesson 26 | Java Lesson 27 | Java Lesson 28 | Java Lesson 29 | Java Lesson 30 | Java Lesson 31 | Java Lesson 32 | Java Lesson 33 | Java Lesson 34 | Java Lesson 35 | Java Lesson 36 | Java Lesson 37 | Java Lesson 38 | Java Lesson 39 | Java Lesson 40 | Java Lesson 41 | Java Lesson 42 | Java Lesson 43 | Java Lesson 44 | Java Lesson 45 | Java Lesson 46

Java Lesson 31: Choice, List, and Checkbox controls

The Choice class

  • Is part of the java.awt package

  • Is an extension of the Component class

Object

Component

Choice

  • Creates a pop-up menu from which the user can choose a single item. The current item is displayed as the title of the choice menu. The application can cause some processing to be performed when a selection is made by

  1. Implementing the ItemListener interface

  2. Registering an ItemListener by calling the choice's addItemListener() method

  3. 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.

  • Has a single constructor for instantiating a choice menu having no items. For example,

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).

  • Has many useful methods. Commonly used methods are:

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:

  1. In order to become a registered ItemListener, the class implements the ItemListener interface

  2. 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)

  3. 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.

  4. 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.

  5. 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

  • Is part of the java.awt package

  • Is an extension of the Component class

Object

Component

List

  • 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.

  • Has a several overloaded constructors. For example,

List parts = new List(Cool;

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.

  • Has a number of useful methods. Commonly used methods are:

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:

  1. In order to become a registered ItemListener, the class implements the ItemListener interface

  2. 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)

  3. 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.

  4. 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.

  5. 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.

  6. 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

  • Is part of the java.awt package

  • Is an extension of the Component 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).

  • Has a number of overloaded constructors. For example,

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".

  • Has a number of useful methods. Commonly used methods are:

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:

  1. In order to become a registered ItemListener, the class implements the ItemListener interface

  2. 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)

  3. 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.

  4. 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.

  5. 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.

  6. 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

  1. Which statements are true of a Choice object? (choose two)

  1. it may fire an ActionEvent

  1. it never allows more than one item to be selected at the same time

  2. it inherits the features of the Component class

  3. it may be grouped with other Choice objects in a ChoiceGroup

  4. its event handling is defined within the itemChanged() method of its registered ItemListener

  1. Assuming that all unseen code is correct, what will result from attempting to compile and execute the following statement?

    List myList = new List(6);

  1. a compile error

  1. a runtime error

  2. a List object that can never contain more than 6 items in its menu

  3. a List object that will permit more than one item to be selected at the same time

  4. none of the above

  1. Which of the following expressions can be used to determine the number of items currently selected within a List object named myList? (choose two)

  1. myList.getItemCount()

  1. myList.getSelectedItemCount()

  2. myList.getSelectedIndexes().length

  3. myList.getSelectedItems().length

  4. myList.getItems().length

  1. 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());
}
  1. a compile error will occur at line 2

  2. the salaried checkbox will be "on" and the hourly checkbox will be "off"

  3. the salaried checkbox will be "off" and the hourly checkbox will be "on"

  4. both the salaried and hourly checkboxes will be "on"

  5. both the salaried and hourly checkboxes will be "off"


 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy