簡體   English   中英

未在ActionListener中初始化的變量

[英]Variables not initialized in ActionListener

我正在嘗試讓該程序打印選擇的澆頭和硬皮,以現在設置的方式,它僅打印名稱。 我嘗試將所有字符串初始化為空字符串“”。 但是,無論單擊了什么按鈕,即使支持更改語句,該字符串也始終為空。

這是代碼

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 
}

您所有的if語句都在外部語句內。 是嗎

如果有人想知道,這就是我如何使其工作。

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