0

我有一个带字符串的 JCombobox,我想选择一个。我按照文档上的说明创建了数组,就像那里建议的那样。我需要 String 将其进一步传递给另一个类。如果我想通过s,它不会起作用,因为它是在里面声明的itemStateChanged。如果我尝试设置x = s,也不会工作,因为s是在封闭类型中定义的。所以我的问题基本上是,我该如何String s退出?

    String[] strategies = {"Select Strategy", "FastestAppFirst", "SmallestAppFirst", "BestFitFirst"};

    final JComboBox comboBox = new JComboBox(strategies);
    contentPane.add(comboBox, "2, 2, fill, default");

    String x="";

    comboBox.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {

            String s = comboBox.getSelectedItem().toString();
        }
    });

提前非常感谢。

4

2 回答 2

3

x将您的或变量声明s为类的字段,它将起作用。或者使用这样的东西:

comboBox.addItemListener(new ItemListener() {

    @Override
    public void itemStateChanged(ItemEvent e) {
        String s = comboBox.getSelectedItem().toString();
        //passToAnotherClassMethod(s);
    }
});

阅读教程JComboBox

于 2013-11-11T13:54:28.887 回答
2

定义一个类字段并将选择存储在该字段中。或者在你需要选择的类中定义一个方法,然后调用中的方法itemStateChanged()

targetClass.setSelection(comboBox.getSelectedItem().toString());
于 2013-11-11T13:54:02.833 回答