Focus Gained and Focus Lost event

无人久伴 提交于 2019-12-02 09:49:17

问题


I have 4 JTextfields in my java swing form. The problem is I need to move the Focus from one JTextField to other through java code not by using tab key.

If the Focus gained by JTextField2 means the content in the JTextField2 need to be selected. I don't know how to do this plz put your proper code associate with this issue


回答1:


You can call requestFocusInWindow() for the textfield you want focus.




回答2:


that could be little bit complicated

you have to wrap and delay your Action or ActionListener into invokeLater(), and put inside (most safiest way is to set there follows code lines)

  • JTextField2.setText(JTextField2.getText);

and

  • JTextField2.selectAll();

edit to @Andrew Thompson

private FocusListener fcsListener = new FocusListener() {

        @Override
        public void focusGained(FocusEvent e) {
            dumpInfo(e);
        }

        @Override
        public void focusLost(FocusEvent e) {
            //dumpInfo(e);
        }

        private void dumpInfo(FocusEvent e) {
            System.out.println("Source  : " + name(e.getComponent()));
            System.out.println("Opposite : " + name(e.getOppositeComponent()));
            System.out.println("Temporary: " + e.isTemporary());
            Component c = e.getComponent();//works for editable JComboBox too
            if (c instanceof JFormattedTextField) {
                ((JFormattedTextField) c).selectAll();
            } else if (c instanceof JTextField) {
                ((JTextField) c).selectAll();
            }//both methods not correct required setText(getText()) inside invokeLater
        }

        private String name(Component c) {
            return (c == null) ? null : c.getName();
        }
    };


来源:https://stackoverflow.com/questions/8544461/focus-gained-and-focus-lost-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!