JComboBox question?

I want to know if it is possible to have a JComboBox which contains a list of items, but be able to disable some of the items so that you cannot select them, but you can still see them in the list.  Is this possible and if so, how can I do it?
bjgAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
heyhey_Connect With a Mentor Commented:
what exactly do you want to do ?
1. if you want that disabled items are different color - (for Example PC menus can be disabled and become gray - they still receive the selection but they don't fire 'action events') - you can adjust the color by implementing your own ListCellRenderer (there are many examples out there)

2. if you want not to perform any actions - that's your logic - you receive the 'selection chaged' event, check if this selection is allowed and if not - don't do anything ...

both 1. and 2. functionality can be implemented in a common class that extends JCombobox

3. if you need to have some kind of separators (separator between different groups of items), so that disabled item (separator) does not receive the selection - i think there is no easy way to implement this with Swing - you have to implement all the functionality by yourself.

if you need more information about CellRenderers, I can send you some source code

hope this helps
  heyhey
0
 
bjgAuthor Commented:
Could u send the source code?  It would probably be beneficial.
0
 
bjgAuthor Commented:
What I want to do is, set the JLabel (ListCellRenderer) for the items I want disabled with setEnabled(false).  I also don't want the ComboBox to fire an itemStateChanged event if you select an item that is disabled.  How can I do this.  Some source code would be helpful.
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
heyhey_Commented:
ok, bjg, I will try to send you an example, but it's 20:00 here, so maybe tomorow ...
if you have more specific problem just post it - it would be easier (and quicker) to answer a question than to build (working :) example
0
 
heyhey_Commented:
hi bjg,

do you still need an example
if you need, i can make one during the weekend and post it here

waiting for answer
 heyhey
0
 
bjgAuthor Commented:
Yeah, I need an example if you could do that for me.  Thanks.
0
 
heyhey_Commented:
/*
This is a quick hack
you can see how to make a CellRenderer and how to overrite the actionPerformed behaviour\
this example is not perfect at all ... :) but you can see how the thigs are going on ...
some importand things
1. because keyboard navigation results actionPerfomed (that is selectinchanged)
on every key pressed you can't jump over 'desabled' item (at least using my approach)
2. there is not easy way to override (partly) the behaviour current ListRenderer -
for example to leave all all the current L&F dependand stuff and change only the color of
some of the items :(. I have an idea, but i've got to test it first
(you can see that the two combo boxes are not exactly the same - but it seems that we
can't ovveride the Current Renderer behaviour  )

Note: its better to implement your own ComboModel, that has methods
 .setData(int i, String data)
 .setEnabled(int i, boolean isEnabled)

but you can do this yourself ...

hope this helps
  heyhey

Note: tested on Win95, JDK 1.1.6, Swing 1.0.2
*/

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import com.sun.java.swing.*;
import com.sun.java.swing.event.*;
//import com.sun.java.swing.border.*;


public class RenderTest extends JPanel
{
    String data1[] = {"first", "second", "third", "fourth"};
    StateItem data2[];

public RenderTest() {
    super();

    data2 = new StateItem[4];
    data2[0] = new StateItem("first", 0);
    data2[1] = new StateItem("second", 1);
    data2[2] = new StateItem("third", 0);
    data2[3] = new StateItem("fourth", 0);
   
    StateComboBox c1 = new StateComboBox(data1);
    StateComboBox c2 = new StateComboBox(data2);
    c2.setRenderer(new StateRenderer());
    LFPanel pan = new LFPanel();
   
    JPanel sub1 = new JPanel();
    sub1.setLayout(new FlowLayout());
   
    setLayout(new GridLayout(2,1,10,10));
    sub1.add(c1);
    sub1.add(c2);
    add(sub1);
    add(pan);
    setDoubleBuffered(true);
 }

public static void main (String[] args) {
    JFrame f = new JFrame();
    f.getContentPane().setLayout(new BorderLayout());
    RenderTest test = new RenderTest();
    f.getContentPane().add(test , BorderLayout.CENTER);
    f.setSize(150,150);
    f.addWindowListener(
    new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    }
    );
    f.pack();
    f.show();

}
}


class StateItem
{
    public Object value;
    public int state;
   
    public StateItem(Object theItem)
    {
        value = theItem;
        state = 0;
    }
    public StateItem(Object theItem, int theState)
    {
        value = theItem;
        state = theState;
    }
}

class StateRenderer extends JLabel implements ListCellRenderer {
    StateItem item;

    public StateRenderer() {
          super();
          setOpaque(true);
    }

   
   public Component getListCellRendererComponent (JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
   {
        if (value instanceof StateItem)  {
            item = (StateItem) value;
              setText((item.value == null) ? "" : item.value.toString());
              if (isSelected) {
                  setBackground(list.getSelectionBackground());
                  setForeground(list.getSelectionForeground());
              }
              else {
                  setBackground(list.getBackground());
                if (item.state != 0) {
                    setForeground(Color.lightGray);
//                    setForeground(UIManager.getColor("List.foreground"));
                } else {
                      setForeground(list.getForeground());
                  }
              }
        }
               setFont(list.getFont());
            return this;
   }
 
}


class StateComboBox extends JComboBox
{
    private EventListenerList listeners = new EventListenerList();
    Object lastGood;

    public StateComboBox (Object[] data)
    {
        super(data);
        super.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e)  {
               checkAction(e);
           }}
        );
    }
   
    public void addActionListener(ItemListener aListener) {
        listeners.add(ItemListener.class,aListener);
    }

    public void removeActionListener(ItemListener aListener) {
        listeners.remove(ItemListener.class,aListener);
    }

    public void checkAction(ActionEvent e)  {
       
        Object o = getModel().getSelectedItem();
        if (o instanceof StateItem) {
            StateItem item = (StateItem) o;
            if (item.state != 0) {
                getModel().setSelectedItem(lastGood);
                return ; // ???
            }
            else
                lastGood = o;
        }
        System.out.println("\naction " + e);
        Object[] list = listeners.getListenerList();
        for ( int i = list.length-2; i>=0; i-=2 ) {
//            ((ActionListener)list[i+1]).actionPerformed(e);
        }

    }
   
}


class LFPanel extends JPanel {

    static String metal= "Metal";
    static String metalClassName = "com.sun.java.swing.plaf.metal.MetalLookAndFeel";

    static String motif = "Motif";
    static String motifClassName = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";

    static String windows = "Windows";
    static String windowsClassName = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";

    JRadioButton metalButton, motifButton, windowsButton;

    public LFPanel() {

    metalButton = new JRadioButton(metal);
    metalButton.setActionCommand(metalClassName);

    motifButton = new JRadioButton(motif);
    motifButton.setActionCommand(motifClassName);

    windowsButton = new JRadioButton(windows);
    windowsButton.setActionCommand(windowsClassName);

    // Group the radio buttons.
    ButtonGroup group = new ButtonGroup();
    group.add(metalButton);
    group.add(motifButton);
    group.add(windowsButton);
    metalButton.setSelected(true);

        // Register a listener for the radio buttons.
    RadioListener myListener = new RadioListener();
    metalButton.addActionListener(myListener);
    motifButton.addActionListener(myListener);
    windowsButton.addActionListener(myListener);

    add(metalButton);
    add(motifButton);
    add(windowsButton);
    }

    /** An ActionListener that listens to the radio buttons. */
    class RadioListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        String lnfName = e.getActionCommand();

            try {
        UIManager.setLookAndFeel(lnfName);
        SwingUtilities.updateComponentTreeUI(getParent());
//      getParent().pack();
            }
        catch (Exception exc) {
        JRadioButton button = (JRadioButton)e.getSource();
        button.setEnabled(false);
        updateState();
                System.err.println("Could not load LookAndFeel: " + lnfName);
            }

    }
    }

    public void updateState() {
     String lnfName = UIManager.getLookAndFeel().getClass().getName();
     if (lnfName.indexOf(metal) >= 0) {
         metalButton.setSelected(true);
     } else if (lnfName.indexOf(windows) >= 0) {
         windowsButton.setSelected(true);
     } else if (lnfName.indexOf(motif) >= 0) {
         motifButton.setSelected(true);
     } else {
         System.err.println("SimpleExample if using an unknown L&F: " + lnfName);
     }
    }
}

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.