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.
There is a listener for the frame's "close button,"
but not for the JButton
.
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.*; public class ButtonDemo extends JFrame { JButton bChange ; // constructor for ButtonDemo ButtonDemo() { // construct a Button bChange = new JButton("Click Me!"); 3. // add the button to the JFrame getContentPane().add( bChange ); 4. 5. } public static void main ( String[] args ) 1. { ButtonDemo frm = new ButtonDemo(); 2. WindowQuitter wquit = new WindowQuitter(); frm.addWindowListener( wquit ); frm.setSize( 200, 150 ); frm.setVisible( true ); } } class WindowQuitter extends WindowAdapter { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } }
main()
.main()
constructs a ButtonDemo
object.JButton
is constructed as part of the ButtonDemo
object.
bChange
refers to the JButton
.ButtonDemo
constructor uses
getContentPane().add( bChange )
to add the button to the frame.
The ButtonDemo
class does not need its own paint()
method because everything in the frame is a 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 it inherited the constructor from its parent class (JFrame), which is enough to do the job. When you add components to a container, you need to define a constructor for the frame.