Java Reference
In-Depth Information
The first point can be worth consideration, but if you are using the MVC pattern, you
might prefer to have the Controller handle the user events. Alternatively, a simple anonymous
class can call a method in the Controller class, making the Controller class less dependent on
the GUI architecture.
The last point can be both good and bad as well—you might not want the code
handling
the event with the code that is
configuring
the View. It might make more sense to keep event-
handling code separate.
If you do decide to have a separate class or method handling events, you might want to
consider using the
setActionCommand
method to set a string by which your component can be
easily identified. The string you set can then be retrieved from the
ActionEvent
handed to the
actionPerformed
method. This is demonstrated in Listing 8-6 in the next section.
The JRadioButton Component
Radio buttons are small buttons that are logically grouped together, but only one of the group
can be active at any given time. This is similar to the way a radio with buttons for several pre-
set stations should only have one button pressed at any given time—you can only listen to one
station at a time.
A simple constructor for a
JRadioButton
could be
JRadioButton serverButton = new JRadioButton("Server");
Other constructors allow for an icon to be used instead of or as well as the text, setting the
initial state of the radio button, and setting an
Action
for the radio button.
As with the
JButton
, an
ActionListener
can be added to each
JRadioButton
. You might
use this if you needed to enable or disable fields dependent on which button a user clicked.
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
isSelected
method to check the user's choice.
For
JRadioButton
s to be effective, several of them should be logically grouped together, so
that only one of the logical group can be selected at any given time. You do this by creating a
ButtonGroup
, and adding the radio buttons to it:
ButtonGroup applicationMode = new ButtonGroup();
applicationMode.add(serverButton);
A complete example of
JButton
s and
JRadioButton
s is demonstrated in Listing 8-6, and
the window it would create is shown in Figure 8-17.
Listing 8-6.
Demonstration of JButton and JRadioButton Components
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyFrame extends JFrame {
private static final String EXIT_COMMAND = "EXIT";
private static final String CLIENT_COMMAND = "CLIENT";
private static final String SERVER_COMMAND = "SERVER";