JAVA - 尝试在类外部执行的操作中使用变量

时间:2017-11-19 10:17:31

标签: java variables actionlistener

我正在尝试访问actionPerformed之外的(double)百分比变量,同时保留它经历的更改。 它是一个下拉菜单,你按下一个确定按钮。一旦你按它,它会计算一个百分比值,然后我想在程序中使用它。

以下是代码片段:

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);
            }
        }
    } 

);

谢天谢地

3 个答案:

答案 0 :(得分:1)

您可以使用putClientProperty(Object,Object)和getClientProperty(Object)函数,如下所示:

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

答案 1 :(得分:1)

遗憾的是,Java不支持闭包,因此您无法修改匿名类范围之外的变量。但是你可以访问最终变量,所以原则上你可以这样做:

class Percentage {
    double p;
}
final Percentage p = new Percentage();

btn.addActionListener(
    new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // [...]
            p.p = 1/5;
            // [...]
        }
    }
);

然后,您可以通过匿名课程之外的p.p访问更新的百分比。 (顺便说一下,它真的是一个“百分比”还是实际上是一个比例?)

但这对Java来说似乎不太惯用,所以干净的解决方案可能只是用私有实例变量和getter创建一个合适的类,并使用它来代替匿名类。

答案 2 :(得分:0)

我认为你真正需要的只是一个静态字段(它可以包含你想要的任何访问修饰符)。所以我认为这样的事情应该有效:

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;
                }

            });
        }
    }