焦点监听事件FocusListener

public class Demo extends JFrame {
    public Demo() {
        setBounds(100, 100, 200, 120);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Container c = getContentPane();
        c.setLayout(new FlowLayout());
        JTextField tf1 = new JTextField();
        JTextField tf2 = new JTextField();
        JTextField tf3 = new JTextField();
        tf1.setColumns(15);
        tf2.setColumns(15);
        tf3.setColumns(15);
        c.add(tf1);
        c.add(tf2);
        c.add(tf3);
        tf1.addFocusListener(new MyFocusListener());//调用自定义焦点监听方法类
        tf2.addFocusListener(new MyFocusListener());
        tf3.addFocusListener(new MyFocusListener());
        setVisible(true);
    }

    //在MyFocusListener上,Alt+Ins,Implement Methods,快速创建方法。有光标为绿,无为红
    class MyFocusListener implements FocusListener {//自定义类,实现焦点监听(一种接口)

        public void focusGained(FocusEvent e) {
            JTextField tf = (JTextField) e.getSource();//获取触发焦点事件的控件,强制转换为文本框
            tf.setBorder(BorderFactory.createLineBorder(Color.GREEN));//绿色边框
        }

        public void focusLost(FocusEvent e) {
            JTextField tf = (JTextField) e.getSource();//获取触发焦点事件的控件,强制转换为文本框
            tf.setBorder(BorderFactory.createLineBorder(Color.RED));//红色边框
        }
    }

    public static void main(String[] args) {
        new Demo();
    }
}

 

posted @ 2018-08-11 17:41  夕西行  阅读(763)  评论(0编辑  收藏  举报