Java Reference
In-Depth Information
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.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);
JList jlist = new JList(model);
JScrollPane scrollPane = new JScrollPane(jlist);
frame.add(scrollPane, BorderLayout.CENTER);
JButton button = new JButton("Add");
frame.add(button, BorderLayout.SOUTH);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
int index = (int)(Math.random()*labels.length);
model.addElement(labels[index]);
}
};
button.addActionListener(actionListener);
frame.setSize(300, 200);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
Note When running the program shown in Listing 13-17, if you share a data model across multiple
JComboBox components, there can't be a different selected element within each component. When an
element is “selected” in one, it's selected in all. This seems to be a bug in the MVC design of the JComboBox .
In addition, because a ListSelectionModel manages selection for the JList , changing the selected
element of a JComboBox has no effect on the selected elements within a JList sharing the same model.
 
Search WWH ::




Custom Search