[英]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.