Java Swing Tutorial - Java JComboBox .setModel (ComboBoxModel < E > aModel)








Syntax

JComboBox.setModel(ComboBoxModel < E > aModel) has the following syntax.

public void setModel(ComboBoxModel &lt; E &gt; aModel)

Example

In the following code shows how to use JComboBox.setModel(ComboBoxModel < E > aModel) method.

//from  ww w .  j a v  a 2s  . c  om
import java.awt.BorderLayout;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {

  public static void main(final String args[]) {
    String labels[] = { "A", "B", "C", "D", "E" };
    final DefaultComboBoxModel model = new DefaultComboBoxModel(labels);

    JFrame frame = new JFrame("Shared Data");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel();
    JComboBox comboBox1 = new JComboBox();
    comboBox1.setModel(model);
    comboBox1.setMaximumRowCount(5);
    comboBox1.setEditable(true);

    JComboBox comboBox2 = new JComboBox(model);
    comboBox2.setMaximumRowCount(5);
    comboBox2.setEditable(true);
    panel.add(comboBox1);
    panel.add(comboBox2);
    frame.add(panel, BorderLayout.NORTH);


    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}