java行为处理ActionEvent的使用--------创建一个窗口,包含两个按钮和一个标签,标签初始值为0,如图所示:
1个回答
展开全部
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);
}
}
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);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询