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 button. 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!"); // add the button to the JFrame getContentPane().add( bChange ); } public static void main ( String[] args ) { ButtonDemo frm = new ButtonDemo(); 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()
asks the system to construct a buttonDemo
object.JButton
is constructed using new
with a constructor,
as with any class.
bChange
refers to the JButton
.buttonDemo
constructor uses
getContentPane().add( bChange )
to add the button to the frame.buttonDemo
class does not have its own paint()
method because everything to be painted is a component.drawString()
in the previous chapter), then you will need to override paint()
.The program in the previous chapter does not define a constructor because it inherits 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.