JComboBox checkmark question

When using a JComboBox the selected item is indicated in the dropdown list with a checkmark. I created a really simple renderer that changes the color of the text based on an attribute of the Object:
public class SupportedObjectComboBoxRenderer extends JLabel implements ListCellRenderer {
  public SupportedObjectComboBoxRenderer() {
  public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
    SupportedObject so = (SupportedObject)value;
    this.setForeground(so.isActive() ? Color.BLACK : Color.GRAY);
    this.setText(so.getName());
    return this;
}The checkmark is no longer displayed. I believe I need to render that myself (in the JLabel). Is that default checkmark icon accessible so that I can load it as a resource? Or is there something else I should be doing to show it?

Is there a way you can change the text color of a JComboBox item without
otherwise disrupting the look and feel?don't know if this will work for you, but worth a try
import java.awt.*;
import javax.swing.*;
class Testing extends JFrame
  JComboBox cbo = new JComboBox(new String[]{"London","Madrid","New York","Rome","Sydney","Washington"});
  public Testing()
    setSize(150,75);
    setLocation(400,300);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    cbo.setRenderer(new MyRenderer());
    JPanel jp = new JPanel();
    jp.add(cbo);
    getContentPane().add(jp);
  public static void main(String args[]){new Testing().setVisible(true);}
class MyRenderer extends DefaultListCellRenderer
  public Component getListCellRendererComponent(JList list,Object value,
                      int index,boolean isSelected,boolean cellHasFocus)
    JLabel lbl = (JLabel)super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
    lbl.setForeground(index%2==0? Color.RED:Color.BLUE);
    return lbl;
}

Similar Messages

  • JComboBox Length question!

    When i use JComboBox,it's length is fixed.Perhaps some items is too long to display,so user can't understand it clearly.So i want find JComboBox that can expand automaticly,if item is long,it will be expanded.I tried several function JComboBox provided,but it's remain as usral.I don't know if some master-hand meets same question! Thanks a lot!

    If you want the List wider, look [url http://www2.gol.com/users/tame/swing/examples/SwingExamples.html]here
    If you want the whole combo wider, use
    myCombo.setMinimumSize(new Dimension(200,20));
    It's also possible to calculate the width of string in a certain font (to plug in above), but you can search for that.

  • JComboBox simple question

    I think is a very simple question, I ve got a JComBox with an array of Strings. Something like this:
    JPanel myPanel;
    JComBox box;
    String levels[]={"Level 1","Level 2","Level 3","Level 4","Level 5"};
    box = new JComboBox (levels);
    myPanel.add(box);
    Ok. My question is: How can I let just the level 1 enable at first, or how can I enable or disable just one level of the JCombox, like level 1 and 2 enable but level 3, 4 and 5 disable.
    Thanks a lot!! Hope someone helps me!!

    I don't think this is possible with a JComboBox. I believe it is with a JMenu and JMenuItems.
    You could only display valid options by adding/deleting them. Or you could handle it in the listener code. ie if they select an invalid option do nothing. This would require you keeping track of which options are valid elsewhere in the code.

  • Retrieving values from a JComboBox - Design question.

    I would like some design guidance on a problem that I am hoping has been solved before. Here is my situation:
    I have a JComboBox that I populate with String values from a database table. The exact set of values to be loaded into the JComboBox varies according values specified elsewhere on the GUI.
    When I select an item from the JComboBox, I need to read the database to retrieve more information. The text is not sufficient for me to identify the data I need, so I need to get the table key from somewhere.
    Is there anyway I can associate my table key with the text value inside the JComboBox and retrieve it when the user selects a drop down value from the JComboBox?
    Many thanks in advance.

    when you load the data from the db, try to get ALL the information needed: item label+item value+description. put this data into a map (a hashmap) for example using a unique identifier. For example, use a numeric index. In this case, the item value should be the index that uniquely identifies your items.
    create a simple bean that encapsulates the item contents: index+value+label, description.
    Doing this will avoid the huge db access occurences.
    hth

  • JCombobox Renderer Question

    I am trying to use a custom renderer for a jcombobox in order to show combobox items in different font color. I get a DefaultListCellRenderer and update it according to my needs (setting font color). When I run the application, the combobox is populated properly. When I select one of the items (say "Red") from the combobox, the item gets selected, but the after the selection the font color of the item that is selected defaults to black (instead of red here). What should I do so that after selecting the item, the selected item is shown in the appropriated font color as indicated by custom renderer.
    Here is the code for the custom renderer.
        private class ColorCmbRenderer implements ListCellRenderer {
            protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
            private final Dimension preferredSize = new Dimension(50, 23);
            public Component getListCellRendererComponent(JList list, Object value,
                                                        int index, boolean isSelected,
                                                        boolean cellHasFocus) {
            JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index,
                                                        isSelected, cellHasFocus);
                switch (index) {
                    case 0: renderer.setText("Black");
                            renderer.setForeground(Color.BLACK);
                            break;
                    case 1: renderer.setText("Red");
                            renderer.setForeground(Color.RED);
                            break;
                    case 2: renderer.setText("Blue");
                            renderer.setForeground(Color.BLUE);
                            break;
                    case 3: renderer.setText("Green");
                            renderer.setForeground(Color.GREEN);
                            break;
                    default: break;
                renderer.setPreferredSize(preferredSize);
                return renderer;
        }Another thing that I wanted to know is whether each of the items in the jcombobox can be associated with individual Action objects by using something like setAction(new HTMLEditorKit.BoldAction()).
    regards,
    Nirvan.

    There are 3 foregrounds to be set.import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.*;
    import javax.swing.plaf.basic.BasicComboBoxRenderer;
    public class ComboColors {
       JComboBox comboBox;
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new ComboColors().makeUI();
       public void makeUI() {
          comboBox = new JComboBox(
                new Object[]{"BLACK", "RED", "BLUE", "GREEN"});
          comboBox.setRenderer(new BasicComboBoxRenderer() {
             private final Color[] colors = {
                Color.BLACK, Color.RED, Color.BLUE, Color.GREEN
             @Override
             public Component getListCellRendererComponent(JList list, Object value,
                   int index, boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value,
                      index, isSelected, cellHasFocus);
                if (index == -1) {
                   index = comboBox.getSelectedIndex();
                setForeground(colors[index]);
                list.setSelectionForeground(colors[index]);
                comboBox.setForeground(colors[index]);
                return this;
          JFrame frame = new JFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.add(comboBox);
          frame.add(new JButton("Dummy"), BorderLayout.SOUTH);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
    }db

  • JComboBox listener question

    Hi,
    I was wondering what kind of listener I would use to detect enter being pressed in a JComboBox.
    I tried an actionListener but this sends actionEvents at far too many times, I want to limit what I'm doing to only when the user presses enter in the JComboBox.
    It seems rather odd that a keyListener can't be used with a JComboBox, or at least according to the API specifications...
    All help is very appreciated!!

    The JComboBox itself just has the text field and then the down arrow, correct? Like if I am writing in that text field I am writing in the JComboBox? Basically all i need is a way to do something when the user presses 'enter', but not when all the other various things that trigger ordinary action events are fired. Using a keyListener to find out whether the key pressed was 'enter' seemed like the best way to do this, but if key events aren't even getting sent when the focus is in the text portion of the JComboBox that may not be the case. If there's anyway i can explain the problem better I'd be happy to do so.
    Thanks

  • JComboBox newbie question

    I cant seem to find out how to add items to my jcombobox using Forte.
    I have this :
    String[] dbId = { "579", "459", "789", "098", "297" };
    jComboBox1.addItem(dbId);
    Where do I put this code to fill the combo box with the String array?
    Steve

    Depends on what application you are building.
    If you are building a standalone application, put those codes in the constructor of your application class.
    If you are building an applet, put those codes in the init() method of your applet.

  • JComboBox Usage Question

    Hi guys,
    I have a JClient form which have two JComboBox (State and City). When the State combo box changes it's value, the City combo box's allowable values would change. Both combo boxes are based on database tables. How can I synchronize these two comboboxes, so when the first box changes its' value then the second box will requery the database and display a different set of allowable values?
    Regards
    Tony

    Shailesh,
    These are my code. With the LOV binding, the combox are binded to table but the city combo will not refresh it's lists after state combo change the value.
    stateCombo.setModel(JUComboBoxBinding.createLovBinding(
    panelBinding, stateCombo, "CustomerView", null,
    "CustomerViewIter", new String[] {"StateId"}, "StateLookupView",
    new String[] {"StateId"}, new String[] {"StateName"}, null, null));
    cityCombo.setModel(JUComboBoxBinding.createLovBinding(
    panelBinding, cityCombo, "CustomerView", null,
    "CustomerViewIter", new String[] {"CityId"}, "CityLookupView",
    new String[] {"CityId"}, new String[] {"CityName"}, null, null));
    stateCombo.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    cityCombo.repaint();
    }); From the datamodel you posted at the beginning, the lovVOname for the second combo should have been CityView1, or in other words you should pick the viewobject that is viewlinked to the master StateVO.
    Here's how it works.
    Once you select a state in the states vo, the viewlinked collection on the detail changes to reflect all cities for that state. The Lov combo should then 'redraw' it's list as a reaction to the rangeRefreshed event from BC4J for the detail VO.

  • JComboBox - 2 questions

    First, does implementing ListCellRenderer in a combo govern what is displayed when the combo popup is displayed or when it's not? If it isn't the popup, how do you take control of what is displayed when the combo's button is clicked and the popup displays? I'd like to display a two-column table in the popup area and I'm not quite where to start.
    Second, anyone have any idea how to stop the default drop down popup from displaying when a combo is clicked? Basically, in another case I'd like to install my own listener and display something unique when the combo is clicked and not have the drop down displayed.
    Any thoughts and help would be appreciated.

    ListCellRenderer only presents a user friendly view of what the value is usually is. For example if you add a JLabel to a combo box, the user sees something like this...
    javax.swing.JLabel[preferredwidth=preferredheight=text="Java Website"font=java.awt.Font[...
    ... which is the result of toString(). But if you use a renderer, you present the user with a label so the user only sees:
    Java Website
    Second point: you can do this roughly by rendering your cell as a JPanel with the layout as a GridLayout(2, 1). I haven't done this before but I think it might work. If it doesn't, you'll have to write a custom combobox. Which you will have to do for your third question.
    Stephen                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Editable JComboBox typeahead question

    I have a editable JComboBox which also does the type ahead....So lets
    say I have 4 elements in combo box INDIA , JAPAN, MOROCCO , USA.
    When the user types M then MOROCCO which is 3rd elements gets highlighted and when user tabs out MOROCCO gets selected. But my requirement is when user types in M then MOROCCO should be highlighted ( which is happening ) but also it should be the first element in the list closest to the combobox rather than being the 3rd element in the drop down.
    Please help ..Thanks

    Well since you want the selected element always be the first element, you can simply use setSelectedIndex(0). But before you setSelectedIndex, you have to getSelectedIndex(). In your example the selected index = 2, so you can get the String Object "Morcco". Then you can rearrange the Object[] within the JComboBox by calling removeAllItems or removeItem and addItem. Oh, also you might want to set up an ItemListener and do the rearranging inside the method
    itemStateChanged(ItemEvent e)
    Hope this Helps :}
    Kenny

  • Design question on inner class

    I have an app, with a JPanel. The way I have it setup right now is the JPanel is an inner class with an overloaded constructor. I call the inner class depending on the arguements. this is done repeatedly in my program.
    My question is: Should I be doing it this way or maybe as a method that returns the updated JPanel? Can this cause serious memory problems?
    example
    private void CreateTextfields(int q, int c){
    // c =      number of choices selected from other JComboBox
    // q =      question selected from combo box
    // questions is the arrylist containing all questions
       AnswerPanel answerPanel;
       answerPanel = null;
       textFieldPanel.removeAll();
    if( questions.isEmpty() && c > 0 ){
             answerPanel = new AnswerPanel(c);
    else if( !questions.isEmpty() && c == 0 ){
             answerPanel = new AnswerPanel(q, listOfAnswers);
    else if( !questions.isEmpty() && c > 0 ){
             clearLogic();
             answerPanel = new AnswerPanel(q, listOfAnswers, c);
             textFieldPanel.add( answerPanel, BorderLayout.CENTER ); Thanks
    Jim

    <<serious memory problems>>
    Probably not. But it seems wasteful to keep creating a new object just to set some properties. Why not make a single AnswerPanel, with overloaded setContents() functions?
    Not that I'm a Swing expert or anything....
    HTH,
    Ken

  • Code explanation sort

    Dear Everyone,
    I am using some really neat code to listen to a group of JComboBoxes.
    The four JComboBoxes in question sit on a JFrame and each of the boxes presents the program user with ten numberical choices, namely 0-9.
    The Listener method for one of the JComboBoxes, named Millennia is shown below:
    Millennia.addItemListener(new ItemListener(){
    public void itemStateChanged(ItemEvent e){
    Millenniaxx = Millennia.getSelectedIndex();
    If anybody can explain to me what the above code does it would be greatly appreciated.
    Thanks

    This code adds a listener to listen to a seelction of an item in the JComboBox, when a selection is made the int Millenniaxx will be equal to the number of the selected item.
    Noah

  • Question about JComboBox

    Hello, I've a little problem with a JComboBox. I'm going to explain what's going wrong:
    I have a MySQL database with a table "Swimmers" (id, name, address,..). I want to show the swimmers in a JComboBox and that's no problem. I just get the id + name of all the swimmers with SQL and put their name into the JComboBox with addItem().
    But when I click on a button "Modify", the user can modify the swimmer he selected in de JComboBox. So it's important that there is a link between the items/swimmers in the JComboBox and the id of the swimmer. And that's my problem...
    With getSelectedIndex(), I can get the index of the selected item. But I don't want to get the index, I want to get the ID of the selected swimmer. So the ID of the selected swimmer in the JComboBox.
    So, a litle example:
    In my database, I have the following items:
    ID                    Name                                Address
    ========================================================
    1                     Jos Vermeulen                   Apenstraat 54, Brussel
    4                     Geert De Greef                   Kerkstraat 1, Antwerpen
    8                      Sandra Geeroms                Blastraat 45, GentThe dropdown likes has the following items:
    Jos Vermeulen      (at index 0)
    Geert De Greef      (at index 1)
    Sandra Geeroms    (at index 2)For example: I select "Geert De Greef" and click on the button "Modify". Than the program has to know that the ID of "Geert De Greef" is 4. So I have to add the ID as a value in the JComboBox.. But how?
    Do you understand what I mean?
    I have to know the ID (in the database) of the selected item.. How can I get it?
    Edited by: geertgreef on Apr 28, 2009 4:17 AM

    How do I have to add the array into the JComboBox?Its no different using an array of Swimmers than it would be using an array of Strings. So just try it.
    An how can I "decide" that only the string that is returned by method toString() has to be visible?Thats the way the default renderer works. Read the Swing tutorial on "How to Use Combo Boxes".
    Again just try it. If you have a problem then you post a question. Don't assume you will have a problem.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.

  • JComboBox, ItemListener, ActionListener questions

    Hallo,
    I have some troubles with a JComboBox:
    I add an ActionListener and an ItemListener to it.
    1.ActionListener problems: if the combo is editable then entering value in the editor and clicling Enter fires 2 actionEvents
    with the combo as source. The difference I noticedbetween them is the actionCommand value:
    "comboBoxChanged"(as from normal select) and "comboBoxEdited"(because of changed value in editor)
    2. ItemListener problem: everything is OK selecting with mouse but if I type text/editable again/ and press enter only the
    ActionListener is called(yes, KeyListener in editor will help). The users also want to point a value with the mouse and press enter on it.
    Again only the action is called.
    Now the questions:
    1.Can I rely on the texts in actionCommand? What should I compare them to if "Yes"/are they localized?/
    2. Is there an easier way then adding a KeyListener to the editor and list component of the combo to catch the Enter if ActionListener cannot be used?
    Thanks in advance
    Mike

    About my question 1: in source of JComboBox these text values seem to be hard-coded.
    So I will use them for now. But I still would appreciate other ideas.
    Thanks
    Mike

  • JComboBox question

    i am using a JComboBox in a JPanel all goes well and it is doing exactly want iwant it to do,
    there is one little thing that is bad though, when the JComboBox closes itselft after a selection has been made, the surface that was beneath the expended JComboBox is just not showing anymore.... instead of the components, the background color is all that is showing...
    any one knows how to prevent this or how to make it refresh what it did?
    i have tried to put inside the itemStateChanged() the following:
    myJFrame.validate();
    or
    myFrame.doLayout();
    myFrame.validate();
    or
    myFrame.repaint();
    but nothing seems to work
    any help would be appreciated, thx
    PoPo

    yes , and the action happens properly
    heres the code :
    public void itemStateChanged( ItemEvent event )
    if(event.getSource() == JComboBoxEssNomComm)
    if(test == 0)
    JLabelEssCouranteReponse.setText((JComboBoxEssNomComm.getSelectedItem()).toString());
    test++;
    else
    JLabelEssCouranteReponse.setText((JComboBoxEssNomComm.getSelectedItem()).toString());
    // insert refresh code here
    those actions do happen properly ... but no refresh will work....

Maybe you are looking for