简体   繁体   English

Java:文本字段FocusListener focusGained执行两次,为什么?

[英]Java: Text Field FocusListener focusGained executes two times, why?

I have a text box and I would like to show a dialog box when text box is focus gain. 我有一个文本框,当文本框为焦点增益时,我想显示一个对话框。 So I wrote following codes. 所以我写了下面的代码。 But when dialog box disposed the dialog box appears again. 但是当对话框放置后,该对话框再次出现。 I tried to debug and check with line break. 我试图调试并检查换行符。 That time it does not execute multiple time but in normal mode it executes multiple time so dialog box appears two times... 那个时间它不会执行多次,但是在正常模式下它将执行多次,因此对话框出现两次...

txt1.addFocusListener(new FocusListener(){

    @Override
    public void focusGained(FocusEvent e) {

        myform f = new myform(null,true);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        if("OK".equals(f.button_state)){
            txt2.requestFocus();   
        }
    }

    @Override
    public void focusLost(FocusEvent e) {                
    }

});

If I place the txt2.requestFocus() before the dialog box visible then multiple execution does not happen. 如果我将txt2.requestFocus()放在对话框可见之前,则不会执行多次。 But I am not convinced. 但是我不相信。 Because I required to keep the cursor in txt1 . 因为我需要将光标保持在txt1

Have you any idea..> 你有什么主意..>

  • FocusListener isn't proper place for code where is created of modifyied container 对于创建修改后的容器的代码,FocusListener不是正确的位置

  • Focus is quite asynchronous, then there any some guarantee with proper ordering of methods 焦点是非常异步的,因此可以保证方法的正确排序

  • Swing GUI creations must be wrapped into invokeLater, more see in Oracle tutorial - Initial Thread 必须将Swing GUI创建包装到invokeLater中,有关更多信息,请参见Oracle教程-Initial Thread

  • only this code snipped will be works in FocusListener 仅此代码片段将在FocusListener中起作用

. wrapped into invokeLater 包装成invokeLater

if("OK".equals(f.button_state)){
     txt2.requestFocus();   
}
  • or setVisible(true); setVisible(true); for myform wrapped into invokLater , but I think that must be prepared before (every JComponents are added, initialized, used and applied LayoutManager , packed ), otherwise nothing guarantee anything, there you can call only 对于包装在invokLater myform ,但是我认为必须事先准备好(添加,初始化,使用和应用LayoutManager每个JComponentspacked ),否则无法保证任何事情,您只能在此处调用

. wrapped into invokeLater 包装成invokeLater

f.setVisible(true);
if("OK".equals(f.button_state)){
      txt2.requestFocus();   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM