Share the Data Model between two JComboBox in Java

Description

The following code shows how to share the Data Model between two JComboBox.

Example


 //from   w  w  w.  ja  va 2  s.  co  m
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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[]) {
    final String labels[] = { "A", "B", "C", "D", "E", "F", "G" };

    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(model);
    comboBox1.setEditable(true);

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

    JButton button = new JButton("Add");
    frame.add(button, BorderLayout.SOUTH);
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        model.addElement("New Added");
      }
    };
    button.addActionListener(actionListener);

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

The code above generates the following result.

Share the Data Model between two JComboBox in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer