📄 eventhandlingdemo1.java
字号:
/**
*A simple but very good event handling program,pay more attention!
*implements Listener Interface
*2004.12.28. xhcprince
*/
import java.awt.*;
import java.awt.event.*;
public class EventHandlingDemo1 extends Frame implements ActionListener
{
private Button b1;
private Label l1;
private int clicked;
final String s = "Number of times button clicked = ";
public EventHandlingDemo1(String strName)
{
super(strName); //pay more attention to the common form of such program!
Panel p = new Panel();
b1 = new Button("Click here");
p.setLayout(new FlowLayout());
p.add(b1);
l1 = new Label(s + clicked, Label.CENTER);
add(p);
add(l1,"North"); //it's l1 not 11 !
b1.addActionListener(this);
/*---------------------------------------------------------------------------
Here,whenever Button b1 is clicked,it generates an event and is notified
to listener object that is "this",this refers to the current class
(Interface for the click of a button is ActionListener).So "this" is an
event listener object and b1 is the event source
---------------------------------------------------------------------------*/
}
/*---------------------------------------------------------------------------
The ActionListener interface declares a single function,
that is the actionPerformed() function,the argument of which is the
object of the class ActionEvent.
---------------------------------------------------------------------------*/
public void actionPerformed(ActionEvent e)
{
String str = e.getActionCommand(); //pay attention!
/*---------------------------------------------------------------------------
The function getActionCommand() returns the label of the button that is
the source of the event
---------------------------------------------------------------------------*/
if("Click here".equals(str)) //pay attention!
{
++clicked;
l1.setText(s + clicked);
}
}
public static void main(String args[])
{
EventHandlingDemo1 obj = new EventHandlingDemo1("Taller:)");
obj.setSize(300,300);
obj.setVisible(true);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -