Java Reference
In-Depth Information
A JComboBox requires little screen space, and the editable form is useful for
allowing the user to choose a value quickly without being limited to the dis-
played values. Typically, the drop-down list would include the choices selected
most often, while the program would allow for other choices as well.
Table 7-6 displays some of the JComboBox methods.
Table 7-6
JComboBox Methods
METHOD
PURPOSE
EXAMPLE
JComboBox()
Constructor method to display drop-
myCombo = new
down list choices that users may click;
JComboBox(stringArray);
may accept a String array of choices
to display
setSelectedIndex()
Sets which item is selected in the
printerListCombo.setSelectedIndex(0);
displayed list of choices; useful for
resetting the JComboBox back to its
default value
addItem()
Adds new items to the drop-down list
colorCombo.addItem("Blue");
getItemCount()
Returns the number of items in the
int howMany =
drop-down list
myCombo.getItemCount();
setEditable()
Determines whether the JComboBox is
editableCombo.setEditable(true);
editable (true) or uneditable (false)
removeItem()
Removes an item from the drop-down
coursesCombo.removeItem(4);
list
Programmers can add commands to, or populate, JComboBoxes with the
addItem() method, as shown in Table 7-6; however, the ability to declare,
construct, and populate a JComboBox in a single line of code makes it easier to
create long lists of options from which users may choose. For example, a typical
interface requesting address information from a user may include a drop-down
list of the 50 states. The String array of two-letter postal codes is available from
many Web sources; therefore, Java programmers easily can create what otherwise
would be a complicated, long segment of code with just a single line.
JComboBox statesCombo = new JComboBox(stateArray);
The Classics on DVD program will employ a JComboBox that will be popu-
lated later in the program.
The third Swing component, a JTextPane , is a text component that displays
with graphic attributes. This component models paragraphs composed of a
series of characters with character attributes. Each paragraph has a logical style
attached to it with default attributes, which can be changed by overriding the
default with the setParagraphAttributes() method . In addition to paragraph
attributes, components and images may be embedded in JTextPanes.
Figure 7-10 displays the code to declare and construct the three Swing
components.
 
Search WWH ::




Custom Search