在内部方法中使用变量声明

时间:2013-09-11 18:38:49

标签: java variables

我有两个ItemListener,它们有内部方法,为每个方法声明一个变量。我想比较upperClass中的两个变量。

这是我的代码:

public class MyFrame extends JFrame {

public MyFrame () { 
    initialize();
}

public void initialize() {
    this.setSize(600,200);
    this.setTitle("Frame");
    this.setLocationRelativeTo(null);

    String [] brothers = {"John", "Francis"};
    String [] sisters = {"Sarah","Diana"};

    JPanel centralPnl = new JPanel();
    this.getContentPane().add(centralPnl, BorderLayout.CENTER);

    final JComboBox broBox = new JComboBox(brothers);
    centralPnl.add(broBox);

    final JComboBox sisBox = new JComboBox(sisters);
    centralPnl.add(sisBox);

    broBox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED)  {
                 String selectedValue = broBox.getSelectedItem().toString();

                //connection to DB to get data; DBConnection is a class that connects to DB
                //and a have getAge method which returns age of brothers in array format
                String[] age = new DBConnection().getAge(selectedValue);                    
                String johnAge = String[0];
            }
        }
    });

    sisBox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {

            if (e.getStateChange() == ItemEvent.SELECTED) {
                String selectedValue = broBox.getSelectedItem().toString();

                //connection to DB to get data; DBConnection is a class that connects to DB
                //and a have getAge method which returns age of sisters in array format
                String[] age = new DBConnection().getAge(selectedValue);                    

                String sarahAge = String[0]
            }
        }
    });
}

我想比较johnAgesarahAge。我该怎么办?

1 个答案:

答案 0 :(得分:1)

更广泛地声明johnAgesarahAge。例如,定义变量,但不要在外部类中初始化它们。您也可以将它们设为实例变量而不是方法局部变量。

public class MyFrame extends JFrame {

    String johnAge;
    String sarahAge;


    public void initialize() {

    ....


    //Item listener {
        johnAge = "whatever";
    }

    //Item listener 2 {
        sarahAge = "whatever";
    }

    ....

    //You have access to them now indefinitely through this class's instance

}

}

我建议您阅读Java中的scope,因为这是一个非常常见的编码问题。