How to color an item in a JComboBox?

I need to color some item of my JComboBox,.
or color the string text or the background of the single item
anyone can help me?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test3 extends JFrame {
  public Test3() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = getContentPane();
    Object[] data = { new ColoredObject(Color.RED,"Hello"),
                      new ColoredObject(Color.BLUE,"World,"),
                      new ColoredObject(Color.CYAN,"These"),
                      new ColoredObject(Color.GREEN,"Are"),
                      new ColoredObject(Color.MAGENTA,"Some"),
                      new ColoredObject(Color.ORANGE,"Colors")
    JComboBox jcb = new JComboBox(data);
    jcb.setRenderer(new ColoredRenderer());
    content.add(jcb, BorderLayout.NORTH);
    setSize(300, 300);
    setVisible(true);
  public static void main(String[] arghs) { new Test3(); }
class ColoredObject {
  Color color;
  Object object;
  public ColoredObject(Color color, Object object) {
    this.color=color;
    this.object=object;
  public Object getObject() { return object; }
  public Color getColor() { return color; }
  public String toString() { return object.toString(); }
class ColoredRenderer extends DefaultListCellRenderer {
  public Component getListCellRendererComponent(JList list, Object value,
                                                int index, boolean isSelected,
                                                boolean hasFocus) {
    Component c = super.getListCellRendererComponent(list, value, index,
        isSelected,hasFocus);
    if (!isSelected && !hasFocus && value instanceof  ColoredObject) {
      c.setBackground(((ColoredObject)value).getColor());
    return c;
}

Similar Messages

  • How to color different elements in the JComboBox

    Hi,
    I have a combo box with say 10 items.I want to colour different items inside the combo box with differrent color.How to do this.?
    thnx & regards
    Neel

    hi,
    Thanks.It worked with the following Rendeerer
    class MyCellRenderer extends JLabel implements ListCellRenderer {
             Vector indexVec=new Vector();
              public MyCellRenderer() {
                  setOpaque(true);
              public MyCellRenderer(Vector indexVec) {
                  setOpaque(true);
                  this.indexVec=indexVec;
              public Component getListCellRendererComponent(JList list,
                                                            Object value,
                                                            int index,
                                                            boolean isSelected,
                                                            boolean cellHasFocus) {
                  setText(value.toString());
                  Color background=Color.WHITE;
                  Color foreground=Color.BLACK;
                 if(indexVec.contains(new Integer(index))){
                      foreground=Color.RED;
                 }else{
                      foreground=Color.GREEN;
                 setBackground(background);
                  setForeground(foreground);
                  return this;
          }but I have a problem now.previously for selection of a element or navigation from one item to the other item in the combo baox i used to get a dark blue background showing in which item I am presently now......but after adding this MyCellRenderer that is gone.
    Please help in what could be the prob....how to set that color..
    thnx
    ~Neel

  • How to edit an item in a JComboBox

    I want the user to be able to edit an item in a combobox box. You select an item, edit in the top, press enter, and viola, the item is renamed.
    I've tried some approaches but they're not working out. Thanks for any ideas. What's the point of having an editable combobox if it doesn't EDIT?!

    Hi,
    should be as easy as:
    String[] patternExamples = {
          "dd MMMMM yyyy",
          "dd.MM.yy",
          "MM/dd/yy",
          "yyyy.MM.dd G 'at' hh:mm:ss z",
          "EEE, MMM d, ''yy",
          "h:mm a",
          "H:mm:ss:SSS",
          "K:mm a,z",
          "yyyy.MMMMM.dd GGG hh:mm aaa"
    JComboBox patternList = new JComboBox(patternExamples);
    patternList.setEditable(true);
    patternList.addActionListener(...);

  • How to insert new Item in JCombox through setEditable?

    Hey guys,
    Is there somebody who can help me on how to insert new Item in the JComboBox through setEditable?
    JComboBox box  = new JComboBox();
    box.addItem("");box.addItem("a");
    box.addItem("b");
    box.setEditable(true);
    When I run it and selected the index 0 which the one which color red, I want to edit it and when I press enter key it will add a new item, but preserving this " box.addItem(""); , what I want is to add like this one, box.addItem("The new text entered"); "
    Can you help me with this one... Thanks

    hello,
    the following demo may help,
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    * comobo.java
    * Version 1.0
    * Date Jan 3, 2006
    * Copyright spatika
    public class comobo extends JFrame implements ActionListener{
         JComboBox jc = new JComboBox();
         DefaultComboBoxModel lm = new DefaultComboBoxModel();
         JButton jb = new JButton("add");
         public comobo(){
              lm.addElement("");
              lm.addElement("1");
              lm.addElement("2");
              lm.addElement("3");
              jc.setModel(lm);
              jc.setEditable(true);
              jb.addActionListener(this);
              getContentPane().add(jb,BorderLayout.NORTH);
              getContentPane().add(jc,BorderLayout.SOUTH);
              pack();
              setVisible(true);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
         public void actionPerformed(ActionEvent i){
              Object text = jc.getSelectedItem();
              jc.setSelectedItem(null);
              lm.addElement(text);
         public static void main(String artgs[]){
              new comobo();
    }thanks
    daya

  • How can I create an alt background color for items in a jlistbox or jtree

    What I'm looking to do is have a white background for say items 1,3,5, etc. and a light yellow background for items 2,4,6, etc. I was wondering how can I set an alternative background color on items in a JTree or a JList

    Use a cell renderer:
    import java.awt.*;
    import javax.swing.*;
    public class ListAlternating extends JFrame
         public ListAlternating()
              String[] items = {"one", "two", "three", "four", "five", "six", "seven"};
              JList list = new JList( items );
              list.setVisibleRowCount(5);
              list.setCellRenderer( new MyCellRenderer() );
              JScrollPane scrollPane = new JScrollPane( list );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              ListAlternating frame = new ListAlternating();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
         class MyCellRenderer extends DefaultListCellRenderer
              public Component getListCellRendererComponent(
                   JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
                   super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                   if (!isSelected)
                        setBackground(index % 2 == 0 ? list.getBackground() : Color.LIGHT_GRAY);
                   return this;
    }

  • Sales order display-how to change color of item with high level 0

    Please does anyone know how can i chenge the color of item with high level 0 in display of sales order in red or yellow so it can be seen better for better searching on page?
    thank you in advance...
    regards..

    You'd probably have to do a modification in SD for that. But what you can do, is make the higher level item not changeable. You could also set the display range to UHAU to only see the main items, do this in transaction VOV8. Or you could change your item category in VOV7 only to show main items.
    good luck

  • How to set different color for items in selectManyCheckbox

    hi,
    I would like to change item text background color for each item on selectManyCheckbox (different for each item).
    It is only 5 items so that could be static reference or select.
    I know only how to change background for all items
    af|selectManyCheckbox::item-text {
        background:orange;
    How to select concrete item text and change color for only them?
    I found similar problem:
    css - Set background color of every individual checkbox of p:selectManyCheckbox - Stack Overflow
    but this dont work for me because I dont have in adf tr structure
    I need somethink like this:
    af|selectManyCheckbox::item-text XXXX - select here one of the item by number on list or id  {
        background:orange;

    hi,
    thanks Alejandro and Federico for answers.
    I use JDev 11.1.1.6. I dont write it in previously post because I think that is a more css then adf problem.
    I have 5 selectItem based on simple List<String> {"text1", "text2", "text3", "text4". "text5"}:
    <af:selectManyCheckbox label="List" id="smc2"
                                               layout="horizontal"
                                               value="#{bean.listInBean}"
                                               autoSubmit="true">
                          <af:selectItem label="text1" value="text1" id="si47"/>
                          <af:selectItem label="text2" value="text2" id="si43"/>
                          <af:selectItem label="text3" value="text3" id="si46"/>
                          <af:selectItem label="text4" value="text4" id="si45"/>
                          <af:selectItem label="text5" value="text5" id="si44"/>
                        </af:selectManyCheckbox>
    and I would like to color first selectItem text to orange, second to red.. etc, The list is a static list. Not would be changed.
    After Alejandro answer I build simple for each element (anyCollection contains item with two fields: textValue and label {(text1,text1), (text2,text2)...}
      <af:forEach items="#{bean.anyCollection}"
                                      var="item">
                            <af:selectItem id="si48" value="#{item.textValue}"  styleClass="yourClassName#{var.index}"
                                           label="#{item.label}"/>
                          </af:forEach>
    And now if I have my var called "item" I can write 5 css style classe yourClassName#{var.index} with different color, but there is a problem:
    Attribute styleClass is not defined for af:selectItem
    If it will be so simple I will just add 5 style classes for each selectItem
    <af:selectItem label="text1" value="text1" id="si47" styleClass="yourClassName0"/>
    <af:selectItem label="text2" value="text2" id="si43" styleClass="yourClassName1"/>
    Should I use other component then adf facer rich?

  • How to select multiple items in JComboBox

    Is it possible to select multiple items in a JComboBox
    if yes, then how to do?
    If no , then is there any other way to acheieve this ?

    Hi
    ComboBoxModel extends ListModel and not ListSelectionModel, so i think JComboBox does not provide multiple selection. But u can try customizing ur combo box.. may be its possible.. not very sure
    Shailesh

  • How come the color of items in some MC can be edited whilst the colors of other MC can't

    How come the color of items in some MC can be edited whilst
    the colors of other MC can't. All layers are unlocked.

    Need more info - could be anything - maybe the object is a
    Drawing Object - or Grouped - or an
    instance of a symbol - or...?
    Chris Georgenes / mudbubble.com / keyframer.com / Adobe
    Community Expert
    nikos_golf wrote:
    > How come the color of items in some MC can be edited
    whilst the colors of other MC can't. All layers are unlocked.

  • How to make the item in different color in a choice?

    if I have a choice and different items, how to make the item in different color?
    like:
    Choice ColorChooser = new Choice();
    ColorChooser.add("100");
    ColorChooser.add("200");
    ColorChooser.add("300");
    I want to show green, red and blue color for item 100, 200 and 300.
    I do not know how to do that, anyone can help?
    Thanks

    Please don't double (and now your up to triple) post. I realize that to you, your problem is the most important thing in the world and it would be nice if you could get several people working on it at the same time. However, the people answering your question do not get paid for it. They are doing it because they want to help someone. Posting several times only shows that you have no respect for them and are only concerned with your problem.

  • How to get any items found upon the fill color?

    How to know any items(like textframe, pathitems) found upon the fill color object in "illustrator cs3" file through scripting. I attached the sample cs3 file(Test.eps) for reference. Please help me.
    Thanks

    Using a couple of property nodes, you can get an array of references for all of the controls on a front panel.  From there, just register the array.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines
    Attachments:
    All Controls Mouse Down.png ‏8 KB

  • How to separate events fired from multiple JComboBox instances

    Hi everybody,
    I have built a form with 2 JComboBox instances: each for separated options.
    String[] items = {"Red", "Blue"};
            JComboBox comboBox1 = new JComboBox(items); // For water color
            JComboBox comboBox2 = new JComboBox(items); // For mountain color
            comboBox1.addActionListener(aListener);
            comboBox2.addActionListener(aListener);
            contentArea.add(comboBox1);
            contentArea.add(comboBox2);How can I distinguish which event is fired from comboBox1 and which event comes from comboBox2. I tried to implement actionPerformed method as follows:
    public void actionPerformed(ActionEvent event) {
            Object eventSource = event.getSource();
            if (eventSource instanceof JComboBox) {
                JComboBox cb = (JComboBox)event.getSource();           
                System.out.println("From JCom "+cb);
                if (cb == comboBox1) {
                    System.out.println("From comboBox1");
        }but it does not work. Java Compiler said: cannot find symbol comboBox1.
    How can I resolve this problem?
    Thanks in advance

    Move the declarations for the comboboxes into class scope so they can be seen from within the "actionPerformed" method.
    class SomeClass
        // instance variable declarations
        // these variables have class scope
        JComboBox comboBox1;
        JComboBox comboBox2;
        void aMethod()
            String[] items = {"Red", "Blue"};
            comboBox1 = new JComboBox(items); // For water color
            comboBox2 = new JComboBox(items); // For mountain color
        }Or you could use the "getActionCommand" and "setActionCommand" (JComboBox) methods to send along a string with the event.
    Another option is to use the Component methods "setName" and "getName" to identify the sender of the event. Or you could use the JComponent "putClientProperty" and "getClientProperty" methods.

  • How can I surrend the focus of Jcombobox in Jtable?

    There are a jcombobox for each row of a jtable. I can click each cell to choose some value from the item list of jcombobox.
    The problem is, when I import data into the table by changing the values of tablemodel, if some cell still hold the focus, the table won't show the new imported data for this specific cell, but keep the old one. Others cells without focus work well.
    For example, originally I choose a "Monday" from the combobox with focus. When I import new data (by clicking some button), for instance "Tuesday", the new data doesn't show in the focused cell.
    So, how can I surrend the focus of this specific cell to other components, for instance, some button?

    In your action for your button, before you update your table with the imported information do the following:
    if (myTable.isEditing())
        myTable.getCellEditor().stopCellEditing();
    }

  • Set Background/Foreground color for Cell Renderer in JComboBox

    Hello,
    I was wondering if there is a way to change default settings for when I browse items under a JComboBox's cell renderer? I want the item's color to change (to what I set it to), when mouse enters the item. As of now, the cell's background color changes to Blue when I enter it. Is this default for JComboBox or might it have been set somewhere, that I need to look into?
    Please let me know if there are ways to do this.
    Thanks!
    Message was edited by:
    programmer_girl

    Here's my SSCCE:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JComboBox;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.text.DefaultHighlighter;
    public class MyComboBoxTest extends JPanel {
          * @param args
         String[] patterns = {"pattern1","pattern2","pattern3"};
         public MyComboBoxTest()
              JPanel patternsPanel = new JPanel();
            setMinimumSize(new Dimension(100, 100));
            JComboBox patternList = new JComboBox(patterns);
            final JTextField editor = (JTextField) patternList.getEditor().getEditorComponent();
            patternList.setEditable(true);
            this.add(patternsPanel);
            patternsPanel.add(patternList);
            patternList.addActionListener(new ActionListener()
                 public void actionPerformed(ActionEvent e)
                      editor.setSelectedTextColor(Color.WHITE);
                      editor.setForeground(Color.WHITE);
                      try{
                           editor.getHighlighter().addHighlight(0, editor.getText().length(),new DefaultHighlighter.DefaultHighlightPainter(Color.BLUE));
                           } catch (Exception ex){
                                ex.getMessage();
            editor.addMouseListener(new MouseAdapter()
                 public void mouseClicked(MouseEvent e)
                      editor.getHighlighter().removeAllHighlights();
                      editor.setForeground(Color.BLACK);
                      editor.setSelectedTextColor(Color.BLACK);
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              JFrame frame = new JFrame("My ComboBox Demo");
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setSize(100, 100);
            frame.getContentPane().add(new MyComboBoxTest());
            frame.setLocation(50, 50);
            frame.pack();
            frame.setVisible(true);
    }

  • How to select multiple items in ListView?

    Is it possible to select multiple items (rows) in ListView? I'm able
    to select only one item at a time.
    I'm running Forte 30F2 on Windows NT 4.0.
    Thanks in advance,
    Ramarao
    Get Your Private, Free Email at http://www.hotmail.com

    Ramarao,
    I talked to Forte support about this recently and they had nothing but
    bad news.
    They said that you cannot select multiple rows in a listview, and that
    this is a
    feature that will be in the next release ( release 4 ).
    I then asked if it was possible for me to highlight a row manually ( and
    do the multiple
    select myself ), and they said that also wasn't possible. This is due
    to the fact that
    there are no displaynode properties that effect display attributes (
    like font or color ).
    They suggested that I try changing the smallicon to show rows that have
    been 'selected'.
    In other words, when you ctrl-click on any particular row, you could put
    an icon at the
    beginning of a row that shows that this row has been clicked on.
    I'm still working on this myself, so I will keep you posted.
    Jeff Pickett
    From: Ramarao P[SMTP:[email protected]]
    Reply To: Ramarao P
    Sent: Tuesday, March 24, 1998 6:22 PM
    To: [email protected]
    Subject: How to select multiple items in ListView?
    Is it possible to select multiple items (rows) in ListView? I'm able
    to select only one item at a time.
    I'm running Forte 30F2 on Windows NT 4.0.
    Thanks in advance,
    Ramarao
    Get Your Private, Free Email at http://www.hotmail.com

Maybe you are looking for

  • Java issue with web analysis

    Hi, Web analysis is taking too long to start on client machines. I had this issue a couple of years ago with java 1.4.10. hyperion came back with a solution to increase the memory java uses on both the server and the client. »Xms128m -Xmx256m -Xss2m

  • Audigy, no sound after rest

    I recently formatted my hard dri've. After I finished installing Windows XP, I got my Sound Blaster Audigy, DR release 2.2. driver from this website. Except whenever I restart my computer, the sound doesn't work and I have to reinstall the driver to

  • 9i - How to save  everything in one tablespace and put back in later?

    I'm trying to do a very simple refresh of a 9i database. Basically shutting it down and copying all the dbfs and redo files, then creating new controlfiles. However, the database that is the source does not have one dbf (and tablespace) that the targ

  • Port number for ReportClientDocument

    Hi While specifying the report app server in ReportClientDocument we specify only the host name/ip. We do not specify the port. Which is the port that is being used to connect and establish the link to the RAS ? Eg: We only do ReportClientDocument re

  • Displaying the Last Query Refresh date/time

    Hello, on a Webi report, is there a way to display the date/time that the underlying info provider was refreshed? Thanks, Nikhi