Reputation: 151
Im in progress making my first GUI program, and run into a little problem. I need to return the String value, so i can use it in the method "saying". This part is a sub class - a class built in another class.. The error return value; gets is: void methods cant return values. I know i have to replace void, but with what?? regards Oliver
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);
}
}
Upvotes: 0
Views: 84
Reputation: 3349
Unless you need the String value elsewhere in your program:
Replace
public void saying(){
System.out.println(value);
}
with
public void saying(String value){
System.out.println(value);
}
And then change
return value;
To
saying(value);
Upvotes: 0
Reputation: 2895
You can make an instance variable and can initilise it in actionPerformed
method like below
private class Eventhandler implements ActionListener{
String value=''
public void actionPerformed(ActionEvent event){
value="newvalue";
// rest code goes here
}
}
you can not change the return type of api defined method
Upvotes: 0
Reputation: 229361
As others have said, you can't return anything from actionPerformed
because that's specified in the ActionListener
interface. Even if you could, it wouldn't do you any good, because you're not the one calling the actionPerformed
function.
What you want to do is give the parent class value
, somehow. One way to do this is to have value
be a field on the parent class. Then you can set it from the actionPerformed
function:
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);
}
}
Note that you can't do this.value = value
in the inner class, because this
in that funcion refers to the Eventhandler
instance. You have to use the ParentClass.this
syntax to get the parent class's this
. Replace ParentClass
with the actual name of your parent class.
A better way might be to have a setValue()
function on the parent class, which the inner Eventhandler
class calls. It depends on what you want to do.
Upvotes: 5