我有几个文本字段,我在它们之间切换。在focusLost()
我打开一个JOptionPane
. 我希望在关闭focusGained()
后执行代码。JOptionPane
即使对话框是模态的,也在关闭focusGained()
之前被调用。JOptionPane
有没有办法解决?
发现了这个类似的问题,但似乎也没有解决。 焦点丢失后推迟事件队列
这是一个代码示例。您会注意到在 JOptionPane 关闭之前打印了“Focus Gained”。
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class ShortTest implements FocusListener
{
private void go()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JTextField text1 = new JTextField();
text1.setName("text1");
text1.addFocusListener(this);
JTextField text2 = new JTextField();
text2.setName("text2");
text2.addFocusListener(this);
panel.add(new JLabel("tex1"));
panel.add(text1);
panel.add(new JLabel("text2"));
panel.add(text2);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String [] args)
{
ShortTest test = new ShortTest();
test.go();
}
@Override
public void focusGained(FocusEvent e)
{
if (!e.isTemporary() && (e.getSource() instanceof JTextField))
{
System.out.println("Focus Gained: " + ((JTextField)e.getSource()).getName());
}
}
@Override
public void focusLost(FocusEvent e)
{
if (!e.isTemporary() && (e.getSource() instanceof JTextField))
{
JOptionPane.showOptionDialog(null, ((JTextField)e.getSource()).getName() + " lost focus", "Title", JOptionPane.DEFAULT_OPTION, 0, null, null, null);
}
}
}