Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable JComboBox items at runtime

1.I have created an JComboBox and Jtable when user select items from JComboBox they are added in the JTable.
2.I dont want to allow the user to select the items that have been previously selected by him in JComboBox.
3.So the selected choices must be disabled (not chooseable). How should i do this? 4.The below code removes that selected item from JComboBox after it has been added in JTable but i am interested in disabling it

        String getchoice=(String)selectedgames_combobox.getSelectedItem();

        DefaultTableModel gamesmodel = new DefaultTableModel(); 

        //adding selected choices from JComboBox in JTable 
        gamesmodel.addColumn("Selected Games");     
        gamesmodel.insertRow(gamesmodel.getRowCount(),new Object[]{ getchoice }) ;  

        //refreshing table
        games_table.setModel(gamesmodel);

        //removing the selected item from JComboBox
        selectedgames_combobox.removeItem(getchoice);
like image 974
Akki Avatar asked Feb 13 '13 11:02

Akki


1 Answers

Assume that you have a list that contains some elements which should be disabled, you need to change appeareance of disabled elements and need to prevent user to select those items. To be able to prevent user to select disabled ones you need to override setSelectedIndex method of JComboBox like this:

public void setSelectedIndex(int index) {
   if (!disabled_items.contains(index)) {
       super.setSelectedIndex(index);
   }
}

Also you can change colors of items in BasicComboBoxRenderer like this:

if (disabled_items.contains(index)) {
     setBackground(list.getBackground());
     setForeground(UIManager.getColor("Label.disabledForeground"));
}

For further details.

like image 163
Ömer Faruk Almalı Avatar answered Sep 30 '22 18:09

Ömer Faruk Almalı