Lecture 6
Lecture 6
Check boxes are useful controls for selecting items from a list. But, what if
your list has 100 items? Do you want 100 check boxes? No, but fortunately,
there is a tool that solves this problem. A list control displays a list of items
(with as many items as you like) from which the user can select one or more
items. Both single item and multiple item selections are supported.
List Properties:
List Methods:
setFont Sets font name, style, size.
setBackground Sets the list background color.
setForeground Sets color of text.
setVisibleRowCount Sets number of rows to display.
clearSelection Unselects specified in the list.
getSelectedIndex Returns a value indicating whether the specified
item is selected.
getSelectedIndices Returns an integer array of indices of selected
items.
setSelectedIndex Selects specified item in a list.
setSelectionMode Establishes selection mode.
isSelectionEmpty Checks to see if any items are selected.
List Event:
The valueChanged event is new in our work. To add a listener for such an
event to a list control named myList, use:
myList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e)
{
myListValueChanged(e);
}
});
The items listed in the list control are defined using the DefaultListModel
object. This model manages a resizable array of information, such as that
used with the list control Such a model (myListModel) is created using:
DefaultListModel myListModel = new DefaultListModel(); Once
created, items are added to the list using the addElement or
insertElementAt methods:
With addElement, the item is added to the end of the list. With
insertElementAt the item will be added at the given index value.
List controls normally list string data types, though other types are possible.
Many times, you want the items in a list control to be sorted, or in
alphabetical order. There are no automatic capabilities within the list control
to maintain sorted lists. If you want such capability, you need to do this
yourself using your Java coding skills.
To remove items from the list, there are three methods: removeElement,
removeElementAt, or removeAllElements. For our example list box, the
respective commands are:
Note, when removing items, that indices for subsequent items in the list
change following a removal.
To view, the last item in this list (zero-based), you would use:
myListModel.getElementAt(myListModel.getSize() 1) Once a list
model is established, it is assigned to the list control (myList) using the
setModel method: myList.setModel(myListModel);
Always be aware of when to work with the list control and when to work
with the list model. The primary thing to remember is that items are added
to and deleted from the list model using indices provided by the list control.
The default value allows multiple range selection. To change to single item
selection in the myList control, use:
myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Typical use of list control:
A very useful container control is the scroll pane. This control is like the
panel control with the added capability of being able to scroll any
component placed on the scroll pane. Hence, a large component can be
placed on a small piece of real estate in a GUI frame. Several Swing
controls rely on the scroll pane to provide scrolling capabilities, including
the JTextArea control described earlier and the JList component just
studied. Both horizontal and vertical scrolling of a control is possible.
Using a scroll pane is relatively easy. Since the idea of the pane is to hold a
component larger than the pane itself, you need to establish how large you
want the pane to be. This is done using the setPreferredSize method, which
in turn uses the Dimension object. What all this means is to set the size of a
scroll pane, myPane, use: JScrollPane myPane = new JScrollPane();
myPane.setPreferredSize(new Dimension(width, height)); where
width and height are the desired dimensions in pixels. Once the pane is
established and sized, you can add components to it. A scroll pane can
have a layout manager like other controls, but usually you just add a
single control to the pane (this control might be a panel control with
many controls). A component (myControl) is added to the scroll pane
using the setViewportView method.
myPane.setViewportView(myControl);
At this point, the added control can be scrolled in the scroll pane it s
that easy! Of course, you need to add the scroll pane to the frame (with
associated gridConstraints) to make this happen:
getContentPane().add(myPane, new gridConstraints()); This is the
first time we have set preferred sizes for components. Up to now, we
have let the grid layout manager determine component size and it seems
to have worked just fine. Once you start setting sizes for components,
occasional strange behavior is seen (you ll see it in Example 3-3).
Sometimes, controls don t show up as you would expect. Many times, if
you set the preferred size for a control in one grid location, you need to
set sizes for all components on the grid. You ll start developing your own
ways to handle these strange behaviors. If something doesn t appear as it
should, the preferred size method is a place to start looking.
Scroll bars may or may not appear in the scroll pane, depending on settings
for the scroll bar policy. To establish the horizontal scrollbar policy, use
the setHorizontalScrollBarPolicy with one of three constants from the
ScrollPaneConstants: HORIZONTAL_SCROLLBAR_AS_NEEDED
Scroll bar appears when hosted component is wider than allocated space
(default).
HORIZONTAL_SCROLLBAR_ALWAYS Scroll bar always appears.
HORIZONTAL_SCROLLBAR_NEVER Scroll bar never appears.
You don t need any code to make the scroll bars work that capability
comes along with the scroll pane.
To add a listener for the actionPerformed event for a combo box control
named myComboBox, use: myComboBox.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent e)
{
myComboBoxActionPerformed(e);
}
});
The combo box has its own list model for adding and removing items from
its drop-down list, making list management easier than that of the list
control. Items are added to the combo box (myComboBox) using the
addItem or insertItemAt methods:
With addItem, the item will be added at the end of the list. With
insertItemAt the item will be added at the given index value.
Like list controls, there is no capability for sorted lists for such lists,
you need to add that capability using code.
To remove items from the combo box, there are three methods:
removeItem, removeItemAt, or removeAllItems. For our example combo
box, the respective commands are:
Note, when removing items, that indices for subsequent items in the list
change following a removal.
To refer to an individual item in the combo box, use the getItemAt method:
myComboBox.getItemAt(index)
and the number of items in the combo box is given by the getItemCount
method: myComboBox.getItemCount();
Let s try to clear up all this new information about list controls, scroll panes
and combo boxes with an example.
Example 3-3
Flight Planner
Start a new empty project in NetBeans. Name the project Flight. Delete
default code in Java file named Flight. In this example, you select a
destination city, a seat location, and a meal preference for airline
passengers. The finished product will look like this:
1. Place a scroll pane (which will hold a list control), two combo boxes,
three labels and two buttons on the frame. The GridBagLayout
arrangement for these controls should be:
Flight Frame:
title Flight Planner
resizable false
citiesLabel:
text Destination City
gridx 0
gridy 0
insets (10, 0, 0, 0)
citiesScrollPane:
preferredSize 150, 100
viewportView citiesList (JList control)
gridx 0
gridy 1
insets (10, 10, 10, 10)
seatLabel:
text Seat Location
gridx 1
gridy 0
insets (10, 0, 0, 0)
seatComboBox:
background WHITE
gridx 1
gridy 1
insets (10, 10, 0, 10)
anchor NORTH
mealLabel:
text Meal Preference
gridx 2
gridy 0
insets (10, 0, 0, 0);
mealComboBox:
editable true
gridx 2
gridy 1
insets (10, 10, 0, 10)
anchor NORTH
assignButton:
text Assign
gridx 1
gridy 2
insets (0, 0, 10, 0)
exitButton:
text Exit
gridx 2
gridy 2
insets (0, 0, 10, 0)
2. We will build the project in the usual stages first code to establish the
basic framework: / *
* Flight.java
*/
package flight;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Flight extends JFrame
{
public static void main(String args[])
{
// construct frame
new Flight().show();
}
public Flight()
{
// create frame
setTitle("Flight Planner");
setResizable(false);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
exitForm(e);
}
});
getContentPane().setLayout(new GridBagLayout());
pack();
Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();
setBounds((int) (0.5 * (screenSize.width -
getWidth())), (int) (0.5 * (screenSize.height -
getHeight())), getWidth(), getHeight());
}
private void exitForm(WindowEvent e)
{
System.exit(0);
}
}
3. We will first add the scroll pane with the cities list control. Add these
class level declarations: JLabel citiesLabel = new JLabel();
JList citiesList = new JList();
JScrollPane citiesScrollPane = new JScrollPane();
Position and add each control to the frame (note how the cities list
control is placed in scroll pane): GridBagConstraints gridConstraints;
citiesLabel.setText("Destination City");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
gridConstraints.insets = new Insets(10, 0, 0, 0);
getContentPane().add(citiesLabel, gridConstraints);
citiesScrollPane.setPreferredSize(new Dimension(150, 100));
citiesScrollPane.setViewportView(citiesList);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 1;
gridConstraints.insets = new Insets(10, 10, 10, 10);
getContentPane().add(citiesScrollPane, gridConstraints); Now, at the
end of the frame constructor, use this code to add elements to the cities
list control and initialize the choice to the top element:
DefaultListModel citiesListModel = new DefaultListModel();
citiesListModel.addElement("San Diego");
citiesListModel.addElement("Los Angeles");
citiesListModel.addElement("Orange County");
citiesListModel.addElement("Ontario");
citiesListModel.addElement("Bakersfield");
citiesListModel.addElement("Oakland");
citiesListModel.addElement("Sacramento");
citiesListModel.addElement("San Jose");
citiesListModel.addElement("San Francisco");
citiesListModel.addElement("Eureka");
citiesListModel.addElement("Eugene");
citiesListModel.addElement("Portland");
citiesListModel.addElement("Spokane");
citiesListModel.addElement("Seattle");
citiesList.setModel(citiesListModel);
citiesList.setSelectedIndex(0);
Try scrolling through the cities using the scroll pane. Do you see how
easy it was to add scrolling capability?
4. Now, we ll add the combo box for picking a seat. Add these class level
declarations: JLabel seatLabel = new JLabel();
seatLabel.setText("Seat Location");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 0;
gridConstraints.insets = new Insets(10, 0, 0, 0);
getContentPane().add(seatLabel, gridConstraints);
seatComboBox.setBackground(Color.WHITE);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 1;
gridConstraints.insets = new Insets(10, 10, 0, 10);
gridConstraints.anchor = GridBagConstraints.NORTH;
getContentPane().add(seatComboBox, gridConstraints); Add code to
the frame constructor to populate the combo box:
seatComboBox.addItem("Aisle");
seatComboBox.addItem("Middle");
seatComboBox.addItem("Window");
seatComboBox.setSelectedIndex(0);
properly:
You can now pick a city and a seat. The moral here: when you re setting
preferred sizes on some controls, but not others, weird things may
happen. Fortunately, the only time we usually need to set preferred sizes
is when using scroll panes.
5. Now, let s add the meal combo box and the two buttons (along with their
methods). Add the class level declarations: JLabel mealLabel = new
JLabel();
Use this code to position and add the controls (and events):
mealLabel.setText("Meal Preference");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 2;
gridConstraints.gridy = 0;
gridConstraints.insets = new Insets(10, 0, 0, 0);
getContentPane().add(mealLabel, gridConstraints);
mealComboBox.setEditable(true);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 2;
gridConstraints.gridy = 1;
gridConstraints.insets = new Insets(10, 10, 0, 10);
gridConstraints.anchor = GridBagConstraints.NORTH;
getContentPane().add(mealComboBox, gridConstraints);
assignButton.setText("Assign");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 2;
gridConstraints.insets = new Insets(0, 0, 10, 0);
getContentPane().add(assignButton, gridConstraints);
assignButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
assignButtonActionPerformed(e);
}
});
exitButton.setText("Exit");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 2;
gridConstraints.gridy = 2;
gridConstraints.insets = new Insets(0, 0, 10, 0);
getContentPane().add(exitButton, gridConstraints);
exitButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
exitButtonActionPerformed(e);
}
});
Use this code in the frame constructor to add choices to the meal combo
box: mealComboBox.addItem("Chicken");
mealComboBox.addItem("Mystery Meat");
mealComboBox.addItem("Kosher");
mealComboBox.addItem("Vegetarian");
mealComboBox.addItem("Fruit Plate");
mealComboBox.setSelectedItem("No Preference");
6. We can now add code to the two event methods. First, the
actionPerformed event for the assignButton: private void
assignButtonActionPerformed(ActionEvent e) {
When the Assign button is clicked, this code forms a confirm dialog box
message by concatenating the selected city (from citiesList), seat choice
(from seatComboBox), and the meal preference (from
mealComboBox).
System.exit(0);
}
For reference purposes, here is the final Flight.java code listing (code
added to basic framework is shaded): / *
* Flight.java
*/
package flight;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public Flight()
{
// create frame
setTitle("Flight Planner");
setResizable(false);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
exitForm(e);
}
});
getContentPane().setLayout(new GridBagLayout());
// position controls
GridBagConstraints gridConstraints;
citiesLabel.setText("Destination City");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 0;
gridConstraints.insets = new Insets(10, 0, 0, 0);
getContentPane().add(citiesLabel, gridConstraints);
citiesScrollPane.setPreferredSize(new Dimension(150, 100));
citiesScrollPane.setViewportView(citiesList);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 0;
gridConstraints.gridy = 1;
gridConstraints.insets = new Insets(10, 10, 10, 10);
getContentPane().add(citiesScrollPane, gridConstraints);
seatLabel.setText("Seat Location");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 0;
gridConstraints.insets = new Insets(10, 0, 0, 0);
getContentPane().add(seatLabel, gridConstraints);
seatComboBox.setBackground(Color.WHITE);
seatComboBox.setPreferredSize(new Dimension(100, 25));
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 1;
gridConstraints.insets = new Insets(10, 10, 0, 10);
gridConstraints.anchor = GridBagConstraints.NORTH;
getContentPane().add(seatComboBox, gridConstraints);
mealLabel.setText("Meal Preference");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 2;
gridConstraints.gridy = 0;
gridConstraints.insets = new Insets(10, 0, 0, 0);
getContentPane().add(mealLabel, gridConstraints);
mealComboBox.setEditable(true);
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 2;
gridConstraints.gridy = 1;
gridConstraints.insets = new Insets(10, 10, 0, 10);
gridConstraints.anchor = GridBagConstraints.NORTH;
getContentPane().add(mealComboBox, gridConstraints);
assignButton.setText("Assign");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 1;
gridConstraints.gridy = 2;
gridConstraints.insets = new Insets(0, 0, 10, 0);
getContentPane().add(assignButton, gridConstraints);
assignButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
assignButtonActionPerformed(e);
}
});
exitButton.setText("Exit");
gridConstraints = new GridBagConstraints();
gridConstraints.gridx = 2;
gridConstraints.gridy = 2;
gridConstraints.insets = new Insets(0, 0, 10, 0);
getContentPane().add(exitButton, gridConstraints);
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
exitButtonActionPerformed(e);
}
});
pack();
Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();
setBounds((int) (0.5 * (screenSize.width - getWidth())), (int) (0.5 *
(screenSize.height - getHeight())), getWidth(), getHeight());
// populate cities
DefaultListModel citiesListModel = new DefaultListModel();
citiesListModel.addElement("San Diego");
citiesListModel.addElement("Los Angeles");
citiesListModel.addElement("Orange County");
citiesListModel.addElement("Ontario");
citiesListModel.addElement("Bakersfield");
citiesListModel.addElement("Oakland");
citiesListModel.addElement("Sacramento");
citiesListModel.addElement("San Jose");
citiesListModel.addElement("San Francisco");
citiesListModel.addElement("Eureka");
citiesListModel.addElement("Eugene");
citiesListModel.addElement("Portland");
citiesListModel.addElement("Spokane");
citiesListModel.addElement("Seattle");
citiesList.setModel(citiesListModel);
citiesList.setSelectedIndex(0);
// populate seats
seatComboBox.addItem("Aisle");
seatComboBox.addItem("Middle");
seatComboBox.addItem("Window");
seatComboBox.setSelectedIndex(0);
// meals
mealComboBox.addItem("Chicken");
mealComboBox.addItem("Mystery Meat");
mealComboBox.addItem("Kosher");
mealComboBox.addItem("Vegetarian");
mealComboBox.addItem("Fruit Plate");
mealComboBox.setSelectedItem("No Preference");
}
Run the application. You may have to correct some compilation errors. My
finished screen with choices I made shows:
And, after clicking Assign, I see: