Java Reference
In-Depth Information
Example 10•15: ItemChooser.java (continued)
// they need it. Here's a button that does that.
JButton report = new JButton("Report");
report.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Note the use of multi-line italic HTML text
// with the JOptionPane message dialog box.
String msg = "<html><i>" +
c1.getName() + ": " + c1.getSelectedValue() + "<br>"+
c2.getName() + ": " + c2.getSelectedValue() + "<br>"+
c3.getName() + ": " + c3.getSelectedValue() + "</i>";
JOptionPane.showMessageDialog(frame, msg);
}
});
// Add the 3 ItemChooser objects, and the Button to the panel
chooserPanel.add(c1);
chooserPanel.add(c2);
chooserPanel.add(c3);
chooserPanel.add(report);
// Add the panel and the message line to the window
Container contentPane = frame.getContentPane();
contentPane.add(chooserPanel, BorderLayout.CENTER);
contentPane.add(msgline, BorderLayout.SOUTH);
// Set the window size and pop it up.
frame.pack();
frame.show();
}
}
}
A Complete GUI
We've looked separately at components, containers, layout management, and
event handling, so now it is time to tie these pieces together and add the addi-
tional details required to create a complete graphical user interface. Example 10-16
lists Scribble.java , a simple paint-style application, pictured in Figure 10-13.
This application relies on the scribbling capabilities of the ScribblePane2 class of
Example 10-12. It places a ScribblePane2 instance within a JFrame container to
create the main application window and then adds a JMenuBar and two JToolBar
components to allow the user to control the application. Scribble uses a JColor-
Chooser to let the user select a drawing color and a JOptionPane to display a con-
firmation dialog when the user asks to quit. You should pay particular attention to
how these five Swing components are used; most full-featured applications use
them in similar ways. Note that Example 10-16 is a complete application; it is
designed to be run standalone, not to be viewed using the ShowComponent pro-
gram. However, the Scribble class is designed as a subclass of JFrame , so that
other applications can instantiate Scribble windows of their own, if they so
choose.
This example also introduces the Action interface, which is a subinterface of
ActionListener . Any Action object can be used as an ActionListener to respond
Search WWH ::




Custom Search