首页 > 编程语言 > 详细

java事件处理

时间:2016-10-17 13:33:22      阅读:156      评论:0      收藏:0      [点我收藏+]

1.ActionEven事件

文本框,按钮,菜单项,密码框,单选按钮都可以出发ActionEvent事件

使用

addActionListener(ActionListener listen1)

来注册监视器

ActionListener本来是一个接口,我们必须写类(或者其他接口)来实现它的唯一方法

actionPerformed(ActionEvent e)

这里的e是事件源给该方法的一个参数,ActionEvent类有两个方法

public Object getSource();//返回事件源的上转型对象的引用
public String getActionCommand()//返回一个相关的“命令”字符串,比如这个ActionEvent是文本框,那就是返回他的文本内容

统计单词字数的一个代码

class Component extends JFrame{
    JTextField test1;
    JButton button1;
    JTextArea testArea1;
    JRadioButton radioButton1,radioButton2;
    ButtonGroup group1;
    Component(){
        init();
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    void init(){
        setLayout(new FlowLayout());
        test1=new JTextField(8);
        button1=new JButton("huang");
        testArea1=new JTextArea(8,24);
        add(test1);
        add(button1);
        add(new JScrollPane(testArea1));
        AListener a=new AListener(test1,button1,testArea1);
        test1.addActionListener(a);//需要import java.awt.event.ActionListener;
        button1.addActionListener(a);
    }
}

class AListener implements ActionListener{
    JTextField test1;
    JButton button1;
    JTextArea testArea1;
    AListener(JTextField test,JButton button,JTextArea testArea){
        test1=test;
        button1=button;
        testArea1=testArea;
    }
    public void actionPerformed(ActionEvent e){
        String a=test1.getText();
        testArea1.append(a+"的长度"+a.length());
    }
}

技术分享

 

java事件处理

原文:http://www.cnblogs.com/vhyc/p/5969231.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!