Java Reference
In-Depth Information
Four essential elements define the
JComboBox
component and its implementation:
A data model for holding the
JComboBox
data, as defined by the
ListModel
interface
•
•
A cell renderer for drawing the elements of the
JComboBox
, as described by the
ListCellRenderer
interface
•
An editor for entering choices not part of the predefined data model, as defined by the
ComboBoxEditor
interface
A keystroke manager for handling keyboard input to select elements of the
JComboBox
, as
described by the
KeySelectionManager
interface
•
Many of the
JComboBox
capabilities are shared with the
JList
component. This isn't accidental;
the two components are fairly similar. Let's now look at the
JComboBox
in more detail.
Creating JComboBox Components
Like the
JList
component, the
JComboBox
component has four constructors, allowing you to
create one based on your initial data structure.
Unlike
the
JList
component, the default model
used by the array and
Vector
constructor permits adding and removing data elements.
public JComboBox()
JComboBox comboBox = new JComboBox();
public JComboBox(Object listData[])
String labels[] = { "Chardonnay", "Sauvignon", "Riesling", "Cabernet", "Zinfandel",
"Merlot", "Pinot Noir", "Sauvignon Blanc", "Syrah", "Gewürztraminer"};
JComboBox comboBox = new JComboBox(labels);
public JComboBox(Vector listData)
Vector vector = aBufferedImage.getSources();
JComboBox comboBox = new JComboBox(vector);
public JComboBox(ComboBoxModel model)
ResultSet results = aJDBCStatement.executeQuery("SELECT columnName FROM tableName");
DefaultComboBoxModel model = new DefaultComboBoxModel();
while (result.next())
model.addElement(results.getString(1));
JComboBox comboBox = new JComboBox(model);
JComboBox Properties
After you create a
JComboBox
component, you can modify each of its many properties. Table 13-10
shows the 22 properties of
JComboBox
.