我有一个包含两个组件的简单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);
}
}
}
答案 0 :(得分:4)
还需要验证(和存储)
您可以在JTextField上使用InputVerifier
。它将在传输焦点之前验证文本字段中的文本。如果数据无效,焦点将保留在文本字段中。
编辑:
如果在失去焦点时数据无效,我可以删除此行为,而是将文本字段还原为上一个值吗?
不使用JTextField而是使用JFormattedTextField,它会将数据恢复为之前的值。您不需要使用InputVerifier。阅读How to Use Formatted Text Fields上Swing教程中的部分,了解更多信息和示例。