Example Two: SwingApplication

 < Day Day Up > 

graphics/cd_icon.gif

Let's look at another simple program, SwingApplication (see Figure 2). [3] Each time the user clicks the button ( JButton ), the label ( JLabel ) is updated.

[3] To run SwingApplication using Java Web Start, click the SwingApplication link on the RunExamples/learn.html page on the CD. You can find the source files here: JavaTutorial/uiswing/learn/example-1dot4/index.html#SwingApplication .

Figure 2. The simple GUI of SwingApplication presents a JButton and a JLabel .

graphics/02fig02.gif

Look and Feel

The screenshots in Figure 3 show the GUI of the SwingApplication , each one with a different look and feel.

Figure 3. Four different look and feels.

graphics/02fig03.gif

Version Note: The appearance of many look and feels changes from release to release. For example, in v1.5 we expect the Java look and feel to use slightly different colors and decorations, though components will stay the same size as before.


Swing allows you to specify which look and feel your program usesJava, GTK+, Windows, and so on. The code in boldface type in the following snippet shows you how SwingApplication specifies that it should use the Java look and feel:

 String lookAndFeel = null; ...  lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();  ... try {  UIManager.setLookAndFeel(lookAndFeel);  } catch (Exception e) { }  ...// Create and show the GUI...  

This code essentially says, "I don't care what the user has chosen . Use the cross-platform (Java) look and feel." You can learn more in the section How to Set the Look and Feel (page 628) in Chapter 9.

Setting up Buttons and Labels

Like most GUIs, the SwingApplication GUI contains a button and a label. (Unlike most GUIs, that's about all that SwingApplication contains.) Here's the code that initializes the button:

 JButton button = new JButton("I'm a Swing button!"); button.setMnemonic('i'); button.addActionListener(/*... an action listener...*/); 

The first line creates the button. The second sets the letter " i " as the mnemonic that the user can use to simulate a button click. For example, in the Java look and feel, typing Alt-i does this. The third line registers an event handler for the button click, as discussed later in this section.

Here's the code that initializes and manipulates the label:

  ...// where instance variables are declared:  private static String labelPrefix = "Number of button clicks: "; private int numClicks = 0;  ...// in GUI initialization code:  final JLabel label = new JLabel(labelPrefix + "0    "); ... label.setLabelFor(button);  ...// in the event handler for button clicks:  label.setText(labelPrefix + numClicks); 

It's pretty straightforward, except for the line that invokes the setLabelFor method. That code exists solely as a hint to assistive technologies, such as screen readers, that the label describes the button. [4]

[4] Assistive technologies enable people with disabilities to use computers. For more information, see How to Support Assistive Technologies (page 519) in Chapter 9.

Now that you know how to set up buttons, you also know much of what's needed to set up check boxes and radio buttons, as they all inherit from the AbstractButton class.

Check boxes are similar to radio buttons, but by convention their selection models are different. Any number of check boxes in a groupnone, some, or allcan be selected. On the other hand, by convention only one button can be selected from a group of radio buttons. Figure 4 shows two programs that use check boxes and radio buttons. You'll get a closer look at radio buttons in Example Six: VoteDialog (page 30) later in this chapter.

Figure 4. Standard two-state buttons: check boxes and radio buttons.

graphics/02fig04.gif

Adding Components to Containers

SwingApplication groups its label and button in a container (a JPanel ) before adding the components to the frame. Here's the code that initializes the container:

 JPanel panel = new JPanel(new GridLayout 0,1); panel.add(button); panel.add(label); panel.setBorder(BorderFactory.createEmptyBorder(...)); 

The first line creates the container and assigns it a layout manager an object that determines the size and position of each component added to the container. The code new GridLayout(0,1) creates a layout manager that forces the container's contents to be displayed in a single column, with every component having the same size.

The next two lines add the button and the label to the container. The last line adds a border to it. We'll discuss the border in the next section.

Layout management concepts are discussed in Chapter 4, Laying Out Components within a Container (page 87). Individual layout managers, such as GridLayout , are covered in Chapter 8, Layout Manager Reference (page 457).

Adding Borders around Components

Figure 5 is another look at the SwingApplication GUI.

Figure 5. SwingApplication with the JPanel shaded.

graphics/02fig05.gif

Notice that there's extra space surrounding the JPanel on all four edges. Here's the code that adds the padding:

 panel.setBorder(BorderFactory.createEmptyBorder(                                 30, //top                                 30, //left                                 10, //bottom                                 30) //right                                 ); 

The code creates and sets a border that provides some empty space around the container's contents30 extra pixels on the top, left, and right and 10 extra pixels on the bottom. Borders are a feature that JPanel inherits from the JComponent class. A Border object isn't a JComponent ; instead, it's used by one or more JComponent s to paint the component's edges. You can learn more in How to Use Borders (page 535) in Chapter 9.

Handling Events

Every time the user types a character or pushes a mouse button, an event occurs. Any object can be notified of the event. All it has to do is implement the appropriate interface and be registered as an event listener on the appropriate event source.

SwingApplication class implements an event handler for button clicks (action events). Here's the relevant code:

 public class SwingApplication implements ActionListener {     ...         JButton button = new JButton("I'm a Swing button!");         button.addActionListener(this);     ....     public void actionPerformed(ActionEvent e) {         numClicks++;         label.setText(labelPrefix + numClicks);    } } 

Every event handler requires three pieces of code:

  1. In the declaration for the event handler class, one line of code specifies that the class either implements a listener interface or extends a class that implements a listener interface. For example:

     public class MyClass implements ActionListener { 
  2. Another line of code registers an instance of the event handler class as a listener on one or more components. For example:

     someComponent.addActionListener(instanceOfMyClass); 
  3. The event handler class has code that implements the methods in the listener interface. For example:

     public void actionPerformed(ActionEvent e) {  ...//code that reacts to the action...  } 

In general, to detect when the user clicks an onscreen button (or does the keyboard equivalent) a program must have an object that implements the ActionListener interface. The program must register this object as an action listener on the button (the event source) using the addActionListener method. When the user clicks the onscreen button, the button fires an action event. This results in the invocation of the action listener's actionPerformed method (the only method in the ActionListener interface). (See Figure 6.) The single argument to the method is an ActionEvent object that gives information about the event and its source.

Figure 6. When the user clicks a button, the button's action listeners are notified.

graphics/02fig06.gif

Swing components can generate many kinds of events. Table 1 lists a few examples.

Table 1. Some Events and Associated Event Listeners

Act that Results in the Event

Listener Type

User clicks a button, presses Enter while typing in a text field, or chooses a menu item

ActionListener

User closes a frame (main window)

WindowListener

User presses a mouse button while the cursor is over a component

MouseListener

User moves the mouse over a component

MouseMotionListener

Component becomes visible

ComponentListener

Component gets the keyboard focus

FocusListener

Table or list selection changes

ListSelectionListener

Any property in a component changes such as the text on a label

PropertyChangeListener

Note: Event-handling code executes in a single thread, the event-dispatching thread . This ensures that each event handler finishes execution before the next one starts. The actionPerformed method in the preceding example executes in the event-dispatching thread. Painting code also executes in the event-dispatching thread. Therefore, event-handling code should execute quickly so that the program's GUI stays responsive . If an event takes too long to execute, the GUI will freezethat is, it won't repaint or respond to mouse clicks. Chapter 5, Writing Event Listeners (page 107), has more information.


 < Day Day Up > 


JFC Swing Tutorial, The. A Guide to Constructing GUIs
The JFC Swing Tutorial: A Guide to Constructing GUIs (2nd Edition)
ISBN: 0201914670
EAN: 2147483647
Year: 2004
Pages: 171

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net