In the body of the actionPerformed()
method.
We will fill in the actionPerformed()
body so that clicking the button
changes the color of the frame.
To change the color of the content pane of a frame,
use the method
setBackground( Color c )
.
You can use one of the pre-defined colors like this:
getContentPane().setBackground( Color.red )
Other pre-defined colors are Color.green
, Color.blue
,
Color.yellow
, and so on.
Here is the interesting part of our program:
public class ButtonDemo2 extends JFrame implements ActionListener
{
JButton bChange;
public ButtonDemo2()
{
getContentPane().setLayout( new FlowLayout() );
bChange = new JButton("Click Me!");
bChange.addActionListener( this );
getContentPane().add( bChange )
}
public void actionPerformed( ActionEvent evt)
{
getContentPane()._________________________
repaint(); // ask the system to paint the screen.
}
public static void main ( String[] args )
{
. . . . .
}
}
The repaint()
will be explained in the next page.