Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

JComboBox question?

Posted on 1998-11-11
7
Medium Priority
?
421 Views
Last Modified: 2008-02-01
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?
0
Comment
Question by:bjg
  • 4
  • 3
7 Comments
 
LVL 16

Accepted Solution

by:
heyhey_ earned 200 total points
ID: 1227215
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
 

Author Comment

by:bjg
ID: 1227216
Could u send the source code?  It would probably be beneficial.
0
 

Author Comment

by:bjg
ID: 1227217
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 16

Expert Comment

by:heyhey_
ID: 1227218
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
 
LVL 16

Expert Comment

by:heyhey_
ID: 1227219
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
 

Author Comment

by:bjg
ID: 1227220
Yeah, I need an example if you could do that for me.  Thanks.
0
 
LVL 16

Expert Comment

by:heyhey_
ID: 1227221
/*
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

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Suggested Courses

963 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question