0

焦点在 jtextfield 中(第一个)我单击桌面上的其他位置(使框架失去焦点)如果我单击另一个 jtextfield(第二个),我希望它获得焦点而不经过第一个(不幸的是,情况并非如此)。

这是我在单击来自其他应用程序的第二个 jtextfield 时获得的:

windowGainedFocus
focus gained on first
mouse pressed on second
focus gained on second

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class FocusIssue extends JFrame implements WindowFocusListener {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new FocusIssue().setVisible(true);
            }
        });
    }

    public FocusIssue() {

        JTextField tf = new JTextField(10);
        tf.setName("first");
        tf.addFocusListener(new GFocusListener());
        tf.addMouseListener(new GMouseAdapter());

        getContentPane().add(tf, "North");

        tf = new JTextField(10);
        tf.addFocusListener(new GFocusListener());
        tf.addMouseListener(new GMouseAdapter());
        tf.setName("second");
        getContentPane().add(tf, "South");

        addWindowFocusListener(this);

        pack();
    }

    @Override
    public void windowGainedFocus(WindowEvent e) {
        System.out.println("windowGainedFocus");
    }

    @Override
    public void windowLostFocus(WindowEvent e) {
        System.out.println("windowLostFocus");
    }

    public class GFocusListener extends FocusAdapter {
        @Override
        public void focusGained(FocusEvent e) {
            System.out.println("focus gained on " + ((JComponent) e.getSource()).getName());
        }
    }

    public class GMouseAdapter extends MouseAdapter {
        @Override
        public void mousePressed(MouseEvent e) {
            System.out.println("mouse pressed on " + ((JComponent) e.getSource()).getName());
        }
    }
}
4

0 回答 0