第二种情况下的对话框为 null

Dialog in second case is null

提问人:Draxstep 提问时间:5/3/2023 最后编辑:Federico klez CullocaDraxstep 更新时间:5/3/2023 访问量:33

问:

我有以下代码,问题出在最后一个开关中,在第一种情况下,我创建了对话框,我在屏幕上看到了它,到目前为止一切都很好。在对话框中有一个名为“btnAddWord2”的按钮,对应于开关的第二种情况,我按下它并识别它,问题是当我尝试在这种情况下引用“dialog”时,它会将其视为空,这可能是一个可能的解决方案?

public class App implements ActionListener{
    
    private Frame frame;
    private Dialog dialog;
    private JsonFileManager file;
    private Dictionary dictionary;
    
    public App() {
        
        dialog = null;
        frame = new Frame(this);
        
    }

    public static void main(String[] args) {
        
        new App();
        
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        
        dictionary = new Dictionary();
        int op = 0;
        
        if(frame.getRbtEng().isSelected() == true) {
            
            op = 1;
            
            try {
                
                file = new JsonFileManager(op);
                
            } catch (IOException e1) {
                
                e1.printStackTrace();
            }
            
            dictionary.setDictionary(file.getDictionary().getDictionary());
            
        }else if(frame.getRbtFra().isSelected() == true) {
            
            op = 2;
            try {
                
                file = new JsonFileManager(op);
                
            } catch (IOException e1) {
                
                e1.printStackTrace();
            }
            
            dictionary.setDictionary(file.getDictionary().getDictionary());
            
        }
        
        if(e.getActionCommand().equals("btnTranslate")) {
            
            int pos = dictionary.searchWord(frame.getTextFieldEsp().getText());
            String translation = dictionary.getDictionary().get(pos).getTranslation();
            frame.getTextFieldTrans().setText(translation);
            
        }
        
        switch(e.getActionCommand()) {
        
        case "btnAddWord":
            
            dialog = new Dialog(this);
            dialog.setVisible(true);
            
            break;
            
        case "btnAddWord2":
            
            if (dialog != null && !dialog.isVisible()) {
                
                System.out.println("Enter");
                Definition definition = new Definition(dialog.getTxtField1().getText(), dialog.getTxtField2().getText());
                dictionary.getDictionary().add(definition);
                dialog.dispose();
            }
          
            break;
            
        default:
            break;
        }
            
    }
}

首先,我尝试在该案例中创建一个条件,以便它检查对话框是否为 null,事实上,这是因为它从未执行过 if 中的代码。 我唯一希望的是对话框不再是 null,并且根据代码,信息在对话框的文本字段中设置

java 用户界面 null 对话框 switch-statement

评论

1赞 g00se 5/3/2023
这看起来像古代的 Java (, ),除非你有由 Swing 制作的自定义类。它是什么?你是btnAddWord2处理程序中的对话框 - 为什么?您可能也应该发布代码FrameDictionarydispose()Dialog

答: 暂无答案