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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
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
do you still need an example
if you need, i can make one during the weekend and post it here
waiting for answer
heyhey
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().setLayo ut(new BorderLayout());
RenderTest test = new RenderTest();
f.getContentPane().add(tes t , 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 getListCellRendererCompone nt (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.getSele ctionBackg round());
setForeground(list.getSele ctionForeg round());
}
else {
setBackground(list.getBack ground());
if (item.state != 0) {
setForeground(Color.lightG ray);
// setForeground(UIManager.ge tColor("Li st.foregro und"));
} else {
setForeground(list.getFore ground());
}
}
}
setFont(list.getFont());
return this;
}
}
class StateComboBox extends JComboBox
{
private EventListenerList listeners = new EventListenerList();
Object lastGood;
public StateComboBox (Object[] data)
{
super(data);
super.addActionListener(ne w ActionListener() {
public void actionPerformed(ActionEven t e) {
checkAction(e);
}}
);
}
public void addActionListener(ItemList ener aListener) {
listeners.add(ItemListener .class,aLi stener);
}
public void removeActionListener(ItemL istener aListener) {
listeners.remove(ItemListe ner.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("\nacti on " + e);
Object[] list = listeners.getListenerList( );
for ( int i = list.length-2; i>=0; i-=2 ) {
// ((ActionListener)list[i+1] ).actionPe rformed(e) ;
}
}
}
class LFPanel extends JPanel {
static String metal= "Metal";
static String metalClassName = "com.sun.java.swing.plaf.m etal.Metal LookAndFee l";
static String motif = "Motif";
static String motifClassName = "com.sun.java.swing.plaf.m otif.Motif LookAndFee l";
static String windows = "Windows";
static String windowsClassName = "com.sun.java.swing.plaf.w indows.Win dowsLookAn dFeel";
JRadioButton metalButton, motifButton, windowsButton;
public LFPanel() {
metalButton = new JRadioButton(metal);
metalButton.setActionComma nd(metalCl assName);
motifButton = new JRadioButton(motif);
motifButton.setActionComma nd(motifCl assName);
windowsButton = new JRadioButton(windows);
windowsButton.setActionCom mand(windo wsClassNam e);
// Group the radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(metalButton);
group.add(motifButton);
group.add(windowsButton);
metalButton.setSelected(tr ue);
// Register a listener for the radio buttons.
RadioListener myListener = new RadioListener();
metalButton.addActionListe ner(myList ener);
motifButton.addActionListe ner(myList ener);
windowsButton.addActionLis tener(myLi stener);
add(metalButton);
add(motifButton);
add(windowsButton);
}
/** An ActionListener that listens to the radio buttons. */
class RadioListener implements ActionListener {
public void actionPerformed(ActionEven t e) {
String lnfName = e.getActionCommand();
try {
UIManager.setLookAndFeel(l nfName);
SwingUtilities.updateCompo nentTreeUI (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(tr ue);
} else if (lnfName.indexOf(windows) >= 0) {
windowsButton.setSelected( true);
} else if (lnfName.indexOf(motif) >= 0) {
motifButton.setSelected(tr ue);
} else {
System.err.println("Simple Example if using an unknown L&F: " + lnfName);
}
}
}
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().setLayo
RenderTest test = new RenderTest();
f.getContentPane().add(tes
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 getListCellRendererCompone
{
if (value instanceof StateItem) {
item = (StateItem) value;
setText((item.value == null) ? "" : item.value.toString());
if (isSelected) {
setBackground(list.getSele
setForeground(list.getSele
}
else {
setBackground(list.getBack
if (item.state != 0) {
setForeground(Color.lightG
// setForeground(UIManager.ge
} else {
setForeground(list.getFore
}
}
}
setFont(list.getFont());
return this;
}
}
class StateComboBox extends JComboBox
{
private EventListenerList listeners = new EventListenerList();
Object lastGood;
public StateComboBox (Object[] data)
{
super(data);
super.addActionListener(ne
public void actionPerformed(ActionEven
checkAction(e);
}}
);
}
public void addActionListener(ItemList
listeners.add(ItemListener
}
public void removeActionListener(ItemL
listeners.remove(ItemListe
}
public void checkAction(ActionEvent e) {
Object o = getModel().getSelectedItem
if (o instanceof StateItem) {
StateItem item = (StateItem) o;
if (item.state != 0) {
getModel().setSelectedItem
return ; // ???
}
else
lastGood = o;
}
System.out.println("\nacti
Object[] list = listeners.getListenerList(
for ( int i = list.length-2; i>=0; i-=2 ) {
// ((ActionListener)list[i+1]
}
}
}
class LFPanel extends JPanel {
static String metal= "Metal";
static String metalClassName = "com.sun.java.swing.plaf.m
static String motif = "Motif";
static String motifClassName = "com.sun.java.swing.plaf.m
static String windows = "Windows";
static String windowsClassName = "com.sun.java.swing.plaf.w
JRadioButton metalButton, motifButton, windowsButton;
public LFPanel() {
metalButton = new JRadioButton(metal);
metalButton.setActionComma
motifButton = new JRadioButton(motif);
motifButton.setActionComma
windowsButton = new JRadioButton(windows);
windowsButton.setActionCom
// Group the radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(metalButton);
group.add(motifButton);
group.add(windowsButton);
metalButton.setSelected(tr
// Register a listener for the radio buttons.
RadioListener myListener = new RadioListener();
metalButton.addActionListe
motifButton.addActionListe
windowsButton.addActionLis
add(metalButton);
add(motifButton);
add(windowsButton);
}
/** An ActionListener that listens to the radio buttons. */
class RadioListener implements ActionListener {
public void actionPerformed(ActionEven
String lnfName = e.getActionCommand();
try {
UIManager.setLookAndFeel(l
SwingUtilities.updateCompo
// 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()
if (lnfName.indexOf(metal) >= 0) {
metalButton.setSelected(tr
} else if (lnfName.indexOf(windows) >= 0) {
windowsButton.setSelected(
} else if (lnfName.indexOf(motif) >= 0) {
motifButton.setSelected(tr
} else {
System.err.println("Simple
}
}
}
ASKER