1

我有两个ItemListeners,它们具有为每个声明一个变量的内部方法。我想比较上层类中的两个变量。

这是我的代码:

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。我应该怎么办?

4

1 回答 1

1

Declare johnAge and sarahAge more broadly. For example, define the variables, but don't initialize them, in the outer class. You could also make them instance variables instead of method-local variables.

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

}

}

I'd recommend reading up on scope in Java, since this is a really common coding problem.

于 2013-09-11T18:40:11.350 回答