Chapter 28. Writing a Simple JFC Program

Getting started using the Swing classes is pretty simple. Application windows inherit from JFrame, and applets inherit from JApplet. The only difference between Frame and JFrame is that you cannot add components or set the layout directly for JFrame. Instead, you must use the getContentPane method to obtain the container in which you can add components and vary the layout.

getContentPane().setLayout(new BorderLayout());
JButton b = new JButton ("Hi");
getContentPane().add(b);       //add a button to the layout

This is sometimes a bit tedious to type each time, so we recommend retrieving the JPanel from the content pane and then adding all the components to that panel.

JPanel jp = getContentPane()   //get the JPanel
JButton b = new JButton("Hi");
jp.add(b);                     //add components to it

JPanels are containers much like the AWT Panel object, except that they are automatically double-buffered and repaint more quickly and smoothly.

Setting the Look and Feel

If you do not select a look and feel, Swing programs will start up in their own default native look and feel rather than that of Windows, Motif, or the Mac. If you don't want the default look and feel, you must specifically set the look and feel in each program, using a method like that following:

private void setLF() {
        // Force SwingApp to come up in the System L&F
        String laf = UIManager.getSystemLookAndFeelClassName();
        try {
            UIManager.setLookAndFeel(laf);
        } catch (UnsupportedLookAndFeelException exc) {
            System.err.println("UnsupportedLookAndFeel: " + laf);
        } catch (Exception exc) {
            System.err.println("Error " + laf + ": " + exc);
        }
}

The system that generates one of several look and feels and returns self-consistent classes of visual objects for a given look and feel is an example of an Abstract Factory pattern, discussed in Chapter 5.

Setting the Window Close Box

Like the Frame component, the system exit procedure is not called automatically when a user clicks on the Close box. To enable that behavior, you must add a WindowListener to the frame and catch the WindowClosing event. This can be done most effectively by subclassing the WindowAdapter class.

private void setCloseClick() {
        //create a WindowListener to respond to the window close 
          click
        addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
        });
    }

Making a JxFrame Class

Because you will probably always set the look and feel and must always create a Window Adapter to close the JFrame, we have created a JxFrame class that contains those two functions and calls them as part of initialization.

public class JxFrame extends Jframe {
    public JxFrame(String title) Jframe {
     super(title);
     setCloseClick();
     setLF();
    }
}

The setLF and setCloseClick methods are included as well. It is this JxFrame class that we use in virtually all of our examples in this book, to avoid always having to retype the same code.

A Simple Two-Button Program

With these fundamentals taken care of, we can write a simple program with two buttons in a frame, like the one in Figure 28.1.

A simple two-button Swing program.

Figure 28.1. A simple two-button Swing program.

One button switches the color of the background, and the other causes the program to exit. We start by initializing our GUI and catching both button clicks in an actionPerformed method.

public class SimpleJFC extends JxFrame
implements ActionListener {
    private JButton OK, Quit;
    private Color   color;
    private JPanel  jp; 

    public SimpleJFC() {
        super("Simple JFC Program");
        color = Color.yellow;
        setGUI();
    }
    //--------------
    private void setGUI() {
        jp = new JPanel();
        getContentPane().add(jp); 

        //create and add the buttons
        OK =   new JButton("OK");
        Quit = new JButton("Quit");
        OK.addActionListener(this);
        Quit.addActionListener(this); 

        jp.add(OK); 
        jp.add(Quit); 

        setSize(new Dimension(250,100)); 
        setVisible(true); 
  }
  //--------------
  public void actionPerformed(ActionEvent e) {
      Object obj = e.getSource();
        if (obj == OK)
            switchColors();
        if (obj == Quit)
            System.exit(0);
        }

The only remaining part is the code that switches the background colors.

    private void switchColors() {
        if (color == Color.green)
            color = Color.yellow;
        else
            color = Color.green;
        jp.setBackground(color);
        repaint();
    }

That's all there is to writing a basic JFC application. Writing JFC applets are identical except that the applet's init routine replaces the constructor. Now let's look at some of the power of the more common JFC components.

More on JButton

The JButton has several constructors to specify text, an icon, or both:

JButton(String text); 
JButton(Icon icon); 
JButton(String text, Icon icon);

You can also set two other images to go with the button:

set SelectedIcon(Icon icon);       //shown when clicked
setRolloverIcon(Icon icon);        //shown when mouse over

Finally, like all other JComponents, you can use setToolTipText to set the text of a tooltip which will be displayed when the mouse hovers over the button. Here is the code to implement these improvements:

    OK = new JButton("OK", new ImageIcon("color.gif"));
    OK.setRolloverIcon(new ImageIcon("overColor.gif"));
    OK.setToolTipText("Change background color");
    Quit = new JButton("Quit", new ImageIcon("exit.gif"));
    Quit.setToolTipText("Exit from program");

The resulting application window is shown in Figure 28.2 with the tooltip up.

Two picture buttons with the hover tooltip showing.

Figure 28.2. Two picture buttons with the hover tooltip showing.

Programs on the CD-ROM

Program Description  

SwingSimpleSimpleJFC.java

Basic two-button program using JxFrame. 

SwingSimpleSimpleJFC2.java

Two-button program with button images and tooltips. 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset