Reputation: 1
I have made a dropdown box and 2 textFields in java, what i want to do is prevent the user from using the same option again, if they have chosen it once already. below is my code for the dropdown menu and textFields.
JComboBox comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"None", "A", "B", "C"}));
comboBox.setMaximumRowCount(3);
comboBox.setBounds(13, 14, 109, 20);
contentPane.add(comboBox);
textField_1 = new JTextField();
textField_1.setBounds(129, 13, 52, 20);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setColumns(10);
textField_2.setBounds(192, 11, 52, 20);
contentPane.add(textField_2);
I have 3 parameters that the user can choose from, 4 including the None option. say user chooses A, input what I want them to in the textFields, I have a button which adds those values i.e. A, 10, 40 (A was chosen from dropdown, 10 was written in textfield1 and 40 was written in textfield2) to a table. What i want is if the user has chosen A, I want it to be disabled/removed from the dropdown list and they cannot choose it again, if they try clicking on it will give an error and say not allowed.
Thanks.
Upvotes: 0
Views: 283
Reputation: 162
The easiest way I can see is removing the selected option from the comboBox for the following round. My guess is that you do something like this when processing the entry:
selected = combobox.getSelectedItem();
The same way you could use the selected item to remove it from the comboBox:
combobox.removeItem(selected);
And that should do the trick.
Upvotes: 1
Reputation: 1615
If you want to go down the route of disabling individual combo box items you might want to refer to this thread.
Otherwise you could add an event handler to your combo box that would remove the selected item from the component's model. Here's some admittedly inelegant code that does that. You'll need to write a line or two more if you want to stop the user from deleting the 'None' option.
comboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox dropdown = (JComboBox)e.getSource();
DefaultComboBoxModel model = (DefaultComboBoxModel)dropdown.getModel();
model.removeElement(dropdown.getSelectedItem());
}
});
Upvotes: 1