首页 > 解决方案 > JOptionPane 显示消息对话框无法在焦点侦听器中关闭

问题描述

按照对我之前问题的回复中的说明,我已将焦点侦听器添加到我的文本字段中。现在,当按下 tab 键时,文本字段被选中,所以没关系。我在 NumberFormattedException 处理程序中有一个 JOPtionPaneShowMessageDialog 来通知用户文本字段不应留空。但是现在当文本字段为空白时,消息照常出现,但无法关闭。关闭时同时重新打开。如何纠正。请帮助。

   public void focusLost(FocusEvent ae) {
}
   public void focusGained(FocusEvent ae) {
       Object source =ae.getSource();
           if(source instanceof JTextField) {
               gi.selectAll();
               hra.selectAll();
               ss.selectAll();
               pt.selectAll();

'.....code to execute....... '

}else if (source instanceof JButton) ;
    String w= (String) jcb.getSelectedItem();
try{
    String s1=gi.getText();
        int a=Integer.parseInt(s1);
            String s2=ss.getText();
                int b=Integer.parseInt(s2);
                    String s3=pt.getText();
                        int f=Integer.parseInt(s3);
                            String s4=sd.getText();
                                int h=Integer.parseInt(s4);
'....code to execute....'

}catch(NumberFormatException e) {
    JOptionPane.showMessageDialog(jfrm, "No text field should not be left blank . 
        If no amount in a field put  0 (Zero) .", "WARNING ! ",1);
    }
}
public static void main (String args[]) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new IncomeTax();
        }
    });
}
}

'''


'Also I want to show JOptionpaneShowMessageDialog when the user click on the "Help" JMenuItem.My code for the same is as follows, but it is not working. Please give suggestion for the same also.

'''

}else if (source instanceof JMenuItem) {
     if(ae.getSource()== jmiHelp)
         JOptionPane.showMessageDialog(null,"USER MANUAL\n"+"1.Select Age 
             Group.\n"+"2.Enter Gross Income(Salary/Pension)+Surrender Leave 
             salary+ interest income etc.)\n"+"3.Enter deductions admissible to 
             you.\n"+"4.Look tool tip texts for more details.\n"+"5.Click New 
             Scheme or Old Scheme for the respective tax calculation.\n"+"6.No 
             text fields should not be left blank.If no amount put zero.\n");

标签: java

解决方案


问题已由我自己解决。使用 ActionListener 而不是 FocusListener。代替 tab 键,输入键或鼠标单击仅用于第一个实例选择文本。现在 OptionPaneMessage 没问题。


推荐阅读