我有一个包含两个组件的简单 GUI:一个JTextField
和一个自定义组件 ( MyComponent
)。最初,文本字段具有焦点,单击自定义组件会使其具有焦点。
目前我正在使用手动设置焦点requestFocusInWindow
,但focusLost
事件在mousePressed
事件完成后发生。有什么办法可以focusLost
在活动结束之前让活动发生mousePressed
?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Example {
public static void main(String[] args) {
JFrame frame = new JFrame("Example");
frame.setLayout(new FlowLayout());
JTextField textField = new JTextField(10);
textField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent event) {
System.out.println("focusLost");
}
});
frame.add(textField);
frame.add(new MyComponent());
frame.pack();
frame.setVisible(true);
}
private static class MyComponent extends JComponent {
public MyComponent() {
setFocusable(true);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent event) {
requestFocusInWindow();
System.out.println("mousePressed");
}
});
}
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
}
}