views:

35

answers:

1

Hi, I am a little stuck. I can't figure out a much bigger problem than this, so I am going to the roots to eventually build my way up!

I can't print the selected item in the combo box, currently I have an ActionListener for it:

box.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent evt) {
        myBox(evt);
    }
});

...

protected void myBox(ActionEvent evt)
{
    if(myBoxName.getSelectedItem().toString() != null)
    System.out.println(myBoxName.getSelectedItem().toString());
}

I would expect this to print out to the console every time I change the selected item, but it doesn't. This should be so easy though!

Thanks

+1  A: 

I just tried your code and it works fine. Whenever I change selection, the selected text is written to System.out.

The only thing I changed was the check for myBoxName.getSelectedItem().toString() != null, I check for myBoxName.getSelectedItem() != null instead. This should not be related to your problems though.

public class ComboBoxTest {
    private JComboBox comboBox = new JComboBox(
          new DefaultComboBoxModel(new String[] { "Test1", "Test2", "Test3" }));

    public ComboBoxTest() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setSize(200, 100);

        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                myBox(evt);
            }
        });

        frame.getContentPane().add(comboBox);
        frame.setVisible(true);
    }

    protected void myBox(ActionEvent evt) {
        if (comboBox.getSelectedItem() != null) {
            System.out.println(comboBox.getSelectedItem().toString());
        }
    }
}
Peter Lang