Focus Gained and Focus Lost event

前端 未结 2 1154
执笔经年
执笔经年 2021-01-25 18:34

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 ga

相关标签:
2条回答
  • 2021-01-25 18:46

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

    0 讨论(0)
  • 2021-01-25 19:03

    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();
            }
        };
    
    0 讨论(0)
提交回复
热议问题