Reputation: 73
I am trying to access the (double) percentage variable outside my actionPerformed while retaining the changes that it goes through. it is a drop down menu, and an ok button you press. once you press it, it calculates a value for percentage, which then i want to use later on in the program.
Here is a snippet of the code:
btn.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
String currentCountry = (String)cb.getSelectedItem();
double percentage = 0.00;
if(currentCountry.equals("Brazil") || currentCountry.equals("Argentina")) {
cb2.removeAllItems();
for(int i = 0; i < choicesSouthAmerica.length; i++) {
cb2.addItem(choicesSouthAmerica[i]);
}
}
else {
cb2.removeAllItems();
for(int i = 0; i < choicesEurope.length; i++) {
cb2.addItem(choicesEurope[i]);
}
}
btn.setEnabled(false);
btn2.setEnabled(true);
if(currentCountry.equals("Brazil") || currentCountry.equals("Argentina")){
percentage = 1/5;
System.out.println(percentage);
}
else{
percentage = 1/8;
System.out.println(percentage);
}
}
}
);
Thank you kindly
Upvotes: 0
Views: 132
Reputation: 3937
Sadly Java doesn't support closures, so you can not modify variables outside the scope of an anonymous class. But you can access final variables, so in principle you can do something like this:
class Percentage {
double p;
}
final Percentage p = new Percentage();
btn.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
// [...]
p.p = 1/5;
// [...]
}
}
);
Then you can access the updated percentage via p.p
outside of your anonymous class. (Btw. is it really a "percentage" or in fact a ratio?)
But this doesn't seem very idiomatic for Java, so the clean solution is probably just to make a proper class with a private instance variable and a getter and use this instead of the anonymous class.
Upvotes: 1
Reputation: 1112
I think what you actually need is just a static field (it can have whatever access modifiers you want). So something like this I think should work:
public class Test {
static double d = 0;
public static void main(String[] args) {
JButton b = new JButton("ASDF");
b.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
d = 5;
}
});
}
}
Upvotes: 0
Reputation: 314
you could use the putClientProperty(Object,Object) and getClientProperty(Object) functions as follow :
JButton btn = new JButton("Ok");
btn.putClientProperty("percentage",1.0);//or whatever initial value
btn.addActionListener(arg0 -> {
JButton source = (JButton) arg0.getSource();
double per = (double)source.getClientProperty("percentage");
per = (double)10/8;
source.putClientProperty("percentage",per);
});
double percentage = (double)btn.getClientProperty("percentage");//or use it in any other object that has access to the btn object
Upvotes: 1