fucorogu
fucorogu

Reputation: 43

JComboBox ActionListener doesn't work

I'd like to get back every second elements of an array (so in this case 2. and 4.).

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class tester2 extends JFrame{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    JFrame f = new JFrame();
    String [] corps = {"IBM", "Apple", "Oracle", "Google"};
    JComboBox <String> cb = new JComboBox <> ();

    JLabel l1 = new JLabel();

    public tester2() {
        f.setSize(500, 300);
        f.setLayout(new BorderLayout());
        f.setVisible(true);
        f.setTitle("Tester 2");
        f.setLocationRelativeTo(null);

        f.add(cb, BorderLayout.NORTH);
        f.add(l1);

        // Combo
        cb.removeAllItems();
        cb.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                for (int i = 1; i < corps.length; i=+2) {
                     String tempRes = corps[i];
                     System.out.println(tempRes);
                     cb.addItem(tempRes);
                }

            }
        });


    }


    public static void main(String[] args) {  
        new tester2();  
    } 
}   

More details, more details, more details, more details, more details, more details, more details, more details, more details, more details, more details, more details, more details, more details, more details, more details.

Thanks

Upvotes: 0

Views: 1562

Answers (1)

Arnaud
Arnaud

Reputation: 17534

You aren't seeing anything because ActionEvent for a JComboBox is only fired when an item is selected.

Since your combobox is empty, this doesn't happen.

You could put a default value so that your ActionListener gets called.

Also it is probably better to put removeAllItems() in the actionPerformed method, so that you clear the combobox just before populating it .

One last note : the change from i = +2 to i += 2, because i = +2 means i=2, and you go into an infinite loop with index 2 .

    // Combo
    cb.addItem("--filler--");

    cb.addActionListener(new ActionListener() {

        public void actionPerformed(final ActionEvent e) {

            cb.removeAllItems();

            for (int i = 1; i < corps.length; i += 2) {
                String tempRes = corps[i];
                System.out.println(tempRes);
                cb.addItem(tempRes);
            }

        }
    });

Upvotes: 2

Related Questions