Oli*_*Bak 0 java return return-value
我正在制作我的第一个GUI程序,并遇到一个小问题.我需要返回String值,所以我可以在方法"说"中使用它.这部分是一个子类 - 一个在另一个类中构建的类.错误返回值; gets is: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);
}
Run Code Online (Sandbox Code Playgroud)
}
正如其他人所说,你不能返回任何东西,actionPerformed因为在ActionListener界面中指定了.即使你可以,它对你没有任何好处,因为你不是那个调用actionPerformed函数的人.
你想要做的是以value某种方式给予父类.一种方法是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);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,您不能this.value = value在内部类中执行,因为this在该函数中引用了该Eventhandler实例.您必须使用ParentClass.this语法来获取父类this.替换ParentClass为父类的实际名称.
更好的方法可能是setValue()在内部Eventhandler类调用的父类上有一个函数.这取决于你想做什么.
| 归档时间: |
|
| 查看次数: |
80 次 |
| 最近记录: |