Java Swing How to - Add random value to JComboBox








Question

We would like to know how to add random value to JComboBox.

Answer

import java.awt.GridBagLayout;
import java.util.Random;
/*w  w  w.  ja v a2  s . c  o m*/
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new TestPane());
    frame.pack();
    frame.setVisible(true);
  }
}
class TestPane extends JPanel {
  JComboBox comboBox;
  JButton update;

  public TestPane() {
    setLayout(new GridBagLayout());
    update = new JButton("Update");
    comboBox = new JComboBox();

    update.addActionListener(e ->updateCombo());
    updateCombo();

    add(comboBox);
    add(update);
  }

  void updateCombo() {
    DefaultComboBoxModel model = new DefaultComboBoxModel();
    Random rnd = new Random();
    for (int index = 0; index < 10 + rnd.nextInt(90); index++) {
      model.addElement(rnd.nextInt(1000));
    }
    comboBox.setModel(model);
  }

}