There is no listener for the button's events. If there is no listener for a particular type of event, then the program ignores events of that type.
You can click the button, and generate an event, but no listener receives the event.
import java.awt.*; import java.awt.event.*; import javax.swing.*; class ButtonFrame extends JFrame { JButton bChange ; // reference to the button object // constructor for ButtonFrame ButtonFrame() { // construct a Button bChange = new JButton("Click Me!"); 3. A JButton is constructed. // add the button to the JFrame getContentPane().add( bChange ); 4. The JButton is added to the JFrame 5. The default layout manager is used. It puts one big button on the screen. setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE ); 6. The close button is set. } } public class ButtonDemo { public static void main ( String[] args ) 1. The program starts running with main(). { ButtonFrame frm = new ButtonFrame(); 2. main() constructs a ButtonFrame object. frm.setSize( 200, 150 ); 7. The size of the frame is set. frm.setVisible( true ); 8. The frame is made visible. } }
The ButtonFrame
class does not to define a paint()
method because everything in the frame is a Swing component.
The system will automatically paint all components in a container when it needs to.
If special processing is needed,
(as with drawString()
in the previous chapter),
then you need to override paint()
.
The program in the previous chapter did not define a constructor
because the constructor it inherited
from its parent class JFrame
was enough to do the job.
ButtonFrame
adds a components,
and this should be done in a constructor.
What size to you think the button should be? Where should it be placed?