简体   繁体   English

未在ActionListener中初始化的变量

[英]Variables not initialized in ActionListener

I am trying to have this program print the topping and crust selected, the way it is set up now, it only prints the name. 我正在尝试让该程序打印选择的浇头和硬皮,以现在设置的方式,它仅打印名称。 I tried initializing all the strings to be empty strings "". 我尝试将所有字符串初始化为空字符串“”。 But no matter what button was clicked, the string was always empty even though the if statments are suppsed to change them. 但是,无论单击了什么按钮,即使支持更改语句,该字符串也始终为空。

Here is the code 这是代码

public void actionPerformed(ActionEvent e) {
    if(e.getSource() == output){    
        String str2, str3, str4, str5;
        String str1 = txtName.getText();
        if(e.getSource() == optThick){
            str2  = "thick crust";
        }
        else if (e.getSource() == optThin){
             str2 = "thin crust ";
        }
        if(e.getSource() == cbCheese){
            str3 = "Cheese ";
        }
        if(e.getSource() == cbOlives){
             str4 = "Olives ";
        }
        if(e.getSource() == cbTomatoes){
             str5 = "Tomatoes ";
        }

        textArea.setText("Name : " + str1 + "\n" + "Crust: " + str2 + "\n" + "Toppings: " + str3 + str4 + str5); 
    }
}
}
if(e.getSource() == output){    
       // code omitted 
}

All of your if statements are inside the outer statement. 您所有的if语句都在外部语句内。 Is that it ? 是吗

In case anyone was wondering, this is how I got it to work. 如果有人想知道,这就是我如何使其工作。

public void actionPerformed(ActionEvent e) {
    if(e.getSource() == output){    
        String str2 = "", str3 = "", str4 = "", str5 = "";
        String str1 = txtName.getText();
        if(optThick.isSelected()){
            str2  = "Thick crust";
        }
        else if (optThin.isSelected()){
             str2 = "Thin crust ";
        }
        if(cbCheese.isSelected()){
            str3 = "Cheese ";
        }
        if(cbOlives.isSelected()){
             str4 = "Olives ";
        }
        if(cbTomatoes.isSelected()){
             str5 = "Tomatoes ";
        }

        textArea.setText(String.format("Name: %s \nCrust: %s\n Toppings: %s%s%s ",str1, str2, str3, str4, str5)); 
    }
}

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

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