java行为处理ActionEvent的使用--------创建一个窗口,包含两个按钮和一个标签,标签初始值为0,如图所示:

1、实现以下功能:单击“”按钮,则标签的值加一。
2、单击“”按钮时,则标签的值恢复为0.

public class Demo_Login1 extends JFrame implements ActionListener{

private JPanel mainPanel = null;
private JLabel label = null;
private JButton button1 = null;
private JButton button2 = null;
private int count = 0;

public Demo_Login1(){
label = new JLabel(String.valueOf(count));
label.setVerticalAlignment(SwingConstants.CENTER);
label.setHorizontalAlignment(SwingConstants.CENTER);
mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(3,1));
button1 = new JButton("累加1");
button2 = new JButton("清空");
this.add(mainPanel);
button1.addActionListener(this);
button2.addActionListener(this);
mainPanel.add(button1);
mainPanel.add(label);
mainPanel.add(button2);

//设置窗体属性
//大小
this.setSize(50, 150);
//初始位置
this.setLocation(100, 200);
//当关闭窗口的时候,保证jvm也退出
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent e) {
if(e.getSource() == button1){
count++;
}else{
count = 0;
}
label.setText(String.valueOf(count));
}

public static void main(String[] args) {
Demo_Login1 demo = new Demo_Login1();
demo.setVisible(true);
}

}
温馨提示:答案为网友推荐,仅供参考