Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

JComboBox question?

Posted on 1998-11-11
7
Medium Priority
?
420 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

 
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: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say 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

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses

670 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