我正在制作我的第一个 GUI 程序,并遇到了一个小问题。我需要返回字符串值,这样我就可以在“saying”方法中使用它。这部分是一个子类 - 一个构建在另一个类中的类。 错误返回值; gets 是:void 方法不能返回值。我知道我必须替换 void,但是用什么替换?问候奥利弗
private class Eventhandler implements ActionListener{
double amount;
public void actionPerformed(ActionEvent event){
String string = "";
String string1 = "";
if(event.getSource()==item1)
string=String.format(event.getActionCommand());
else if(event.getSource()==item2)
string1=String.format(event.getActionCommand());
JOptionPane.showMessageDialog(null, string);
double fn = Double.parseDouble(string);
double sn = Double.parseDouble(string1);
double amount = fn + sn;
String value = Double.toString(amount);
return value;
}
}
public void saying(){
System.out.println(value);
}
}
最佳答案
正如其他人所说,您无法从 actionPerformed
返回任何内容,因为这是在 ActionListener
接口(interface)中指定的。即使您可以,也不会对您有任何好处,因为您不是调用 actionPerformed
函数的人。
您想要做的是以某种方式为父类提供值
。实现此目的的一种方法是让 value
成为父类中的一个字段。然后您可以从 actionPerformed
函数中设置它:
private class ParentClass {
private String value;
//... stuff ...
private class Eventhandler implements ActionListener{
double amount;
public void actionPerformed(ActionEvent event){
//... stuff ...
ParentClass.this.value = Double.toString(amount);
}
}
public void saying(){
System.out.println(value);
}
}
请注意,您不能在内部类中执行 this.value = value
操作,因为该函数中的 this
引用了 Eventhandler
实例。您必须使用 ParentClass.this
语法来获取父类的 this
。将 ParentClass
替换为父类的实际名称。
更好的方法可能是在父类上使用 setValue()
函数,内部 Eventhandler
类会调用该函数。这取决于您想做什么。
关于java - 我需要帮助才能返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20429034/