Link to home
Start Free TrialLog in
Avatar of bjg
bjg

asked on

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?
ASKER CERTIFIED SOLUTION
Avatar of heyhey_
heyhey_

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bjg
bjg

ASKER

Could u send the source code?  It would probably be beneficial.
Avatar of bjg

ASKER

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.
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
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
Avatar of bjg

ASKER

Yeah, I need an example if you could do that for me.  Thanks.
/*
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);
     }
    }
}