您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes

previous.gif
 (3087 bytes) next.gif
 (2959 bytes)


Content Index Content Page # 17

Example of a button and an action listener

Consider an applet that looks the following running:

When the button is clicked, a message 'ouch' is displayed in a dialogue window:

//<APPLET CODE = "Listener1.class" height = 100 width = 200></APPLET>

import java.applet.Applet;

import java.awt.*;

import java.awt.event.*;

public class Listener1 extends Applet implements ActionListener

{

      String message = "";

public Listener1()

{

      super();

      Button myButton = new Button ("Click me!");

      add(myButton);

      myButton.addActionListener(this);

}

public void actionPerformed (ActionEvent e)

{

            message = "ooch!!!";

            repaint();

}

public void paint(Graphics g)

{

            g.drawString(message,75,50);

}

     

} // class

Back to top

basicline.gif (170 bytes)