tyty5949
tyty5949

Reputation: 1530

JComboBox sets a string and the string then comes back null

I have this little part of a program that uses a JComboBox to select a certain string from it. I found this code on the internet and tried it and it works in the time but when i try to call the string again in a diffrent place after selecting it, it comes back null. Here is the code:

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

It prints out the correct name of the golf course in this situation, but then when i try to call the sr.CourseName again in a diffrent place after selecting it, it prints out null. Help. Thanks in advance.

Upvotes: 1

Views: 120

Answers (1)

FThompson
FThompson

Reputation: 28687

An ActionEvent is passed upon selection as well as deselection, hence the second one being a deselection of one item before the selection of the new item occurs. By using an ItemListener, you can detect whether the event is a selection or a deselection.

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

Upvotes: 1

Related Questions