jfrm.setVisible(true);
}
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new EventDemo();
}
});
}
}
First, notice that the program now imports both the java.awt and java.awt.event
packages. The java.awt package is needed because it contains the FlowLayout class, which
supports the standard flow layout manager used to lay out components in a frame. (See
Chapter 24 for coverage of layout managers.) The java.awt.event package is needed because
it defines the ActionListener interface and the ActionEvent class.
The EventDemo constructor begins by creating a JFrame called jfrm. It then sets the
layout manager for the content pane of jfrm to FlowLayout. Recall that, by default, the content
pane uses BorderLayout as its layout manager. However, for this example, FlowLayout is
more convenient. Notice that FlowLayout is assigned using this statement:
jfrm.setLayout(new FlowLayout());
As explained, in the past you had to explicitly call getContentPane( ) to set the layout
manager for the content pane. This requirement was removed as of JDK 5.
After setting the size and default close operation, EventDemo( ) creates two push
buttons, as shown here:
JButton jbtnAlpha = new JButton("Alpha");
JButton jbtnBeta = new JButton("Beta");
The first button will contain the text "Alpha" and the second will contain the text "Beta."
Swing push buttons are instances of JButton. JButton supplies several constructors. The
one used here is
JButton(String msg)
The msg parameter specifies the string that will be displayed inside the button.
When a push button is pressed, it generates an ActionEvent. Thus, JButton provides
the addActionListener( ) method, which is used to add an action listener. (JButton also
provides removeActionListener( ) to remove a listener, but this method is not used by
the program.) As explained in Chapter 22, the ActionListener interface defines only one
method: actionPerformed( ). It is shown again here for your convenience:
void actionPerformed(ActionEvent ae)
This method is called when a button is pressed. In other words, it is the event handler that
is called when a button press event has occurred.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home