1

我有一个程序的一小部分,它使用 JComboBox 从中选择某个字符串。我在互联网上找到了这段代码并尝试了它,它在一段时间内有效,但是当我在选择它后尝试在不同的地方再次调用该字符串时,它返回 null。这是代码:

    private class courseAL implements ActionListener{
    public void actionPerformed(ActionEvent e) {
        Start_round sr = new Start_round();
        JComboBox cb = (JComboBox)e.getSource();
        sr.CourseName = (String)cb.getSelectedItem();
        System.out.println(sr.CourseName);
    }
}

在这种情况下,它会打印出高尔夫球场的正确名称,但是当我在选择它后尝试在不同的地方再次调用 sr.CourseName 时,它​​会打印出 null。帮助。提前致谢。

4

1 回答 1

1

在选择和取消选择时都会传递一个 ActionEvent,因此第二个是在选择新项目之前取消选择一项。通过使用 ItemListener,您可以检测事件是选择还是取消选择。

private class courseAL implements ItemListener {
    public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
            Start_round sr = new Start_round();
            sr.CourseName = (String) e.getItem();
            // alternate:
            // JComboBox cb = (JComboBox) e.getItemSelectable();
            // sr.CourseName = (String) cb.getSelectedItem();
            System.out.println(sr.CourseName);
        }
    }
}
于 2012-06-07T02:10:14.790 回答