焦点在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());
}
}
}