首页 > 代码库 > Java 界面-焦点事件类

Java 界面-焦点事件类

[ 相关信息]
焦点事件类(FocusEvent)是指用户程序界面的组件失去焦点(即焦点从一个对象转移到另外一个对象)时,就会发生焦点事件。
使用焦点事件必须给组件增加一个 FocusListener 接口的事件处理器,该接口包含以下两个方法:
1)void focusGained(FocusEvent e):当获得焦点时发生。
2)void focusLost(FocusEvent e):当失去焦点时发生。

[具体程序实现]

package sup.orange.learn;import java.awt.*;import java.awt.event.*;/** * Created by re-x on 10/28/14. */public class FocusEventDemo extends Frame{    TextArea textarea;    TextField textfield;    public FocusEventDemo () {        super();        init();    }    public static void main(String[] args) {        new FocusEventDemo();    }    public void init() {        setLayout(new GridLayout(2, 1));        textarea = new TextArea();        textarea.addFocusListener(new FocusListener() {            @Override            public void focusGained(FocusEvent e) {                textarea.setText("gained");            }            @Override            public void focusLost(FocusEvent e) {                textarea.setText("lost");            }        });        textfield = new TextField();        textfield.addFocusListener(new FocusListener() {            @Override            public void focusGained(FocusEvent e) {                textfield.setText("textfield gained");            }            @Override            public void focusLost(FocusEvent e) {                textfield.setText("textfield lost");            }        });        add(textarea);        add(textfield);        addWindowListener(new WindowAdapter() {            @Override            public void windowClosing(WindowEvent e) {                super.windowClosing(e);                dispose();                System.exit(0);            }        });        setSize(200, 500);        setVisible(true);    }}

Java 界面-焦点事件类