简体   繁体   中英

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. 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)); 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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