// Set the applet to use flow layout.
setLayout(new FlowLayout());
// Make two buttons.
jbtnAlpha = new JButton("Alpha");
jbtnBeta = new JButton("Beta");
// Add action listener for Alpha.
jbtnAlpha.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jlab.setText("Alpha was pressed.");
// Add action listener for Beta.
jbtnBeta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent le) {
jlab.setText("Beta was pressed.");
// Add the buttons to the content pane.
// Create a text-based label.
jlab = new JLabel("Press a button.");
// Add the label to the content pane.
There are two important things to notice about this applet. First, MySwingApplet
extends JApplet. As explained, all Swing-based applets extend JApplet rather than Applet.
Second, the init( ) method initializes the Swing components on the event dispatching thread
by setting up a call to makeGUI( ). Notice that this is accomplished through the use of
invokeAndWait( ) rather than invokeLater( ). Applets must use invokeAndWait( ) because
the init( ) method must not return until the entire initialization process has been completed.
In essence, the start( ) method cannot be called until after initialization, which means that
the GUI must be fully constructed.
Inside makeGUI( ), the two buttons and label are created, and the action listeners are
added to the buttons. Finally, the components are added to the content pane. Although
this example is quite simple, this same general approach must be used when building any
Swing GUI that will be used by an applet.
Painting in Swing
Although the Swing component set is quite powerful, you are not limited to using it
because Swing also lets you write directly into the display area of a frame, panel, or one of
Swing's other components, such as JLabel. Although many (perhaps most) uses of Swing
will not involve drawing directly to the surface of a component, it is available for those
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks