您的位置:首页 > 产品设计 > UI/UE

java中的gui实现事件监听

2015-06-23 17:12 609 查看
1、当需要按钮被按下时执行一定的任务,就要向按钮注册动作事件监听器,并为按钮编写动作事件处理代码,即编写实现ActionLisener监听接口的监听器类,并实现actionPerforned方法。设计一个Java GUI应用程序,当点击按钮时,记录点击按钮和点击次数,并显示在窗体中。

/*1、当需要按钮被按下时执行一定的任务,就要向按钮注册动作事件监听器,
并为按钮编写动作事件处理代码,即编写实现ActionLisener监听接口的监听器类,
并实现actionPerforned方法。设计一个Java GUI应用程序,当点击按钮时,
记录点击按钮和点击次数,并显示在窗体中。*/
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public
class
GetClickCountTest {
    public
static void
main(String arg[]){
        new GetClickCountFrame();
       
    }
}
class GetClickCountFrame
extends JFrame implements ActionListener{
    int
count = 0;
    int
count1 = 0;
    private JButton
b1 = new JButton("按钮1");
   
    private JButton
b2 = new JButton("按钮2");
    private JButton
b3 = new JButton("按钮3");
    private JLabel
l1 = new JLabel("显示点击次数");
    private JTextField
t = new JTextField(20);
    public GetClickCountFrame(){
        JFramef = newJFrame();
        JPanelp1 = newJPanel();
        JPanelp2 = newJPanel();
        t.setEditable(false);
        //JLabel l2 = new JLabel();    

        b1.addActionListener(this);    

        b2.addActionListener(this);
        b3.addActionListener(this);
        p1.add(l1);
        p1.add(t);
        p2.add(b1);
        p2.add(b2);
        p2.add(b3);
        f.getContentPane().add(p1,BorderLayout.CENTER);
        f.getContentPane().add(p2,BorderLayout.SOUTH);
        f.setSize(500,300);
        f.setTitle("测试点击次数");
        f.setDefaultCloseOperation(EXIT_ON_CLOSE);
        f.setVisible(true);
    }
 
    @Override
    public
void
actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        Objectsource = e.getSource();
   
        if(source==b1){
           
            count  =
count+1;
            t.setText("按钮1点击了"+count+"次");
        }
        if(source==b2){
            count1 =
count1+1;
            t.setText("按钮2点击了"+count1+"次");
        }
        if(source==b3){
            t.setText("");
            count=0;
            count1=0;
        }
   
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: