[英]How to assure java lost focus event handler finish its work before executing another event handler
[英]How to send focus lost event before mouse pressed event?
我有一个包含两个组件的简单GUI:一个JTextField
和一个自定义组件( MyComponent
)。 最初,文本字段具有焦点,单击自定义组件会使其具有焦点。
目前我使用requestFocusInWindow
手动设置焦点,但focusLost
事件在mousePressed
事件完成后发生。 在mousePressed
事件结束之前有没有办法让focusLost
事件发生?
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);
}
}
}
它还需要验证(和存储)
您可以在JTextField上使用InputVerifier
。 它将在传输焦点之前验证文本字段中的文本。 如果数据无效,焦点将保留在文本字段中。
编辑:
如果丢失焦点时数据无效,是否可以删除此行为,而是将文本字段还原为上一个值?
而不是使用JTextField使用JFormattedTextField,它将数据恢复为以前的值。 您不需要使用InputVerifier。 阅读有关如何使用格式化文本字段的Swing教程中的部分以获取更多信息和示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.