Java Reference
In-Depth Information
Figure 8-17 shows the result from Listing 8-6.
Figure 8-17. Demonstration of JButton and JRadioButton components
The JComboBox Component
Sometimes it makes sense to give users a clear choice of options, rather than requiring them
to type in a choice (which is an error-prone approach). The JComboBox provides us with a sim-
ple box that, when clicked, pops down a list of options from which the user can choose.
If you know the items that are to be used in the list, then there are constructors that allow
you to specify the initial items. Alternatively, you can dynamically add or remove items from
the list using the addItems and removeItems methods, respectively.
As with the JButton and JRadioButton , an ActionListener can be added to each JComboBox .
You might use this if you needed to take action immediately after the user selects an option.
However, it is not always necessary to have an ActionListener —if you don't care about which
button is clicked until after the user performs some other action, then you can use the
getSelectedIndex method to determine the index of the item chosen, or the getSelectedItem
method to find out the object selected.
JComboBox usage is demonstrated in Listing 8-7 shown in the next section, with the
window created displayed in Figure 8-18.
The BorderFactory
So far all the components demonstrated have appeared to the end user to be in the same-
JFrame —there is nothing to logically separate one component (or set of components) from
another.
However, there are times when it makes sense to logically group components together by
drawing a border around them. One of the most common uses of borders is to create a per-
ceived link around several radio buttons or check boxes. We did not put a border around our
radio buttons in the previous section because we want to emphasize that the border only cre-
ates a user perception that the buttons are logically linked—it is possible to have a border
drawn around buttons that are not logically linked, and just creating a border around buttons
does not logically link them.
Unlike with most Swing components, we do not create a border directly. Instead we call
one of the static methods of the BorderFactory class to create a border for us, which we can
then use in a JPanel or JFrame .
Search WWH ::




Custom Search