[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 712
  • Last Modified:

Display a different value than selected in JComboBox

Is it possible to have a JComboBox displaying text in a particular way in its 'list/menu part' but dislaying something different in the editor component?
What I want to have is a list of IDs and names but display only the name in the editor component.
For example I have these items in the combobox's list:
001 | Mr. Smith
002 | Mr. Collins
003 | Mrs. Bloom
...

If 002 is selected I want to display in the editor component only 'Mr. Collins' but not '002 | Mr. Collins'

Thank you,

Dirk
0
dirku
Asked:
dirku
  • 6
  • 6
  • 2
  • +3
1 Solution
 
girionisCommented:
You can get the substring of it, if "s" is the whole String '002 | Mr. Collins' try

s = s.substring(5, s.length())
0
 
TimYatesCommented:
You need to put objects like

class IdNamePair
{
    int id ;
    String name ;
}

into the combomodel, and then write your own renderer (that just draws the name)

Tim
0
 
CEHJCommented:
Just override the toString method of the item ini question to return only the name and not the number
0
Technology Partners: 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!

 
dirkuAuthor Commented:
My fault! I think didn't make really clear what I want.

I have already implemented my own cell renderer in two versions. The first has been used when I stored the ids and names in a Vector of String[2]. String[0] = id, String[1] = name. The second version has been used storing the values (read from a DB) in a specific class CustomerRepresentative.

Version 1 (for String[]):
===============
    class RepresentativeListCellRenderer extends JLabel implements ListCellRenderer
    {
        /**
         * Return a component that has been configured to display the specified
         * value. That component's <code>paint</code> method is then called to
         * "render" the cell.  If it is necessary to compute the dimensions
         * of a list because the list cells do not have a fixed size, this method
         * is called to generate a component on which <code>getPreferredSize</code>
         * can be invoked.
         *
         * @param list         The JList we're painting.
         * @param value        The value returned by list.getModel().getElementAt(index).
         * @param index        The cells index.
         * @param isSelected   True if the specified cell was selected.
         * @param cellHasFocus True if the specified cell has the focus.
         * @return A component whose paint() method will render the specified value.
         * @see javax.swing.JList
         * @see javax.swing.ListSelectionModel
         * @see javax.swing.ListModel
         */
        public Component getListCellRendererComponent(JList list, Object value, int index,
                                                      boolean isSelected, boolean cellHasFocus)
        {
            setOpaque(true);
            if(value == null)
            {
                return null;
            }//end if(value == null)

            final String[] val = (String[])value;
            this.setText(" " + val[0] + "  |  " + val[1]);
            //this.setText(" " + val[1]);
            return this;
        }
    }//end inner class RepresentativeListCellRenderer
    //-----------------------------------------------------------------------

Version 2 (for CustomerRepresentative class):
==============================
    class RepresentativeListCellRenderer extends JLabel implements ListCellRenderer
    {
        /**
         * Return a component that has been configured to display the specified
         * value. That component's <code>paint</code> method is then called to
         * "render" the cell.  If it is necessary to compute the dimensions
         * of a list because the list cells do not have a fixed size, this method
         * is called to generate a component on which <code>getPreferredSize</code>
         * can be invoked.
         *
         * @param list         The JList we're painting.
         * @param value        The value returned by list.getModel().getElementAt(index).
         * @param index        The cells index.
         * @param isSelected   True if the specified cell was selected.
         * @param cellHasFocus True if the specified cell has the focus.
         * @return A component whose paint() method will render the specified value.
         * @see javax.swing.JList
         * @see javax.swing.ListSelectionModel
         * @see javax.swing.ListModel
         */
        public Component getListCellRendererComponent(JList list, Object value, int index,
                                                      boolean isSelected, boolean cellHasFocus)
        {
            setOpaque(true);
            if(value == null)
            {
                return null;
            }//end if(value == null)
            CustomerRepresentative rep = (CustomerRepresentative)value;
            this.setText(rep.getId() + "  |  " + rep.getName());
            return this;
        }
    }//end inner class RepresentativeListCellRenderer
    //-----------------------------------------------------------------------

This way in the combobox's list/popup menu (whatever you call the list which pops up when clicking on the arrow button of the combobox) appears as 001  |  Mr. Smith as well as in the editor component.
What I want is that in the combobox's popum menue the String 001  |  Mr. Smith appears (when the popup menu dropped down/is visible). As soon as the user selects on item of the combobox the selected item's String representation should appear in the editor component of the combobox without all the characters before the name.

I hope I made it clear now what I want. Or did I just misunderstand your suggestions and you already told me how I can achieve what I want??
0
 
CEHJCommented:
Tim's way is the 'correct' way
0
 
JohnnyAffaCommented:
what about using JTable instead?
0
 
TimYatesCommented:
So what you want is a different renderer for the editor bit of the combo as opposed to the drop down bit?
0
 
dirkuAuthor Commented:
Yes, Tim. That's what I need.
0
 
TimYatesCommented:
You can do this:

  class ComboBoxRenderer extends JLabel implements ListCellRenderer
  {
    JComboBox box ;
    public ComboBoxRenderer( JComboBox box )
    {
      this.box = box ;
      setOpaque( true ) ;
      setHorizontalAlignment( CENTER ) ;
      setVerticalAlignment( CENTER ) ;
    }

    public Component getListCellRendererComponent( JList list,
                                                   Object value,
                                                   int index,
                                                   boolean isSelected,
                                                   boolean cellHasFocus )
    {
      if( box.isPopupVisible() )
      {
        setText( "Blah ::" + value ) ;
      }
      else
      {
        setText( value.toString() ) ;
      }

      if( isSelected )
      {
        setBackground( list.getSelectionBackground() ) ;
        setForeground( list.getSelectionForeground() ) ;
      }
      else
      {
        setBackground( list.getBackground() ) ;
        setForeground( list.getForeground() ) ;
      }
      return this ;
    }
  }

thn create the renderer with

  jComboBox.setRenderer( new ComboBoxRenderer( jComboBox ) ) ;

you can see that if "box.isPopupVisible" is checked, and the text is rendered differently depending on the value...

Tim
0
 
dirkuAuthor Commented:
That's a satisfying solution, I will accept.
In this solution the String in the editor bit of the combobox is in the format String in the popupmenue for the moment the popup is visible. Is there another way that NEVER shows the complete String of the popup menu in the editor bit?
0
 
TimYatesCommented:
Don't think so, as the combobox uses the listrenderer, and I couldn't find a way of telling which bit it was rendering :-(

The renderer always thinks it's a List it's rendering :-(
0
 
dirkuAuthor Commented:
In the JDC Forum I've got this answer but I couldn't make it run as supposed:

"The index has a value of -1 when you are renderering the text to be displayed in the editor component. "

Where does your code check the index for a value of -1?

Don't use box.isPopupVisible(), use "index != -1"

What do you think about?
0
 
VenabiliCommented:
dirku,

If the question is not Answered, why you closed it?

Venabili
0
 
TimYatesCommented:
Yup, they were right!

Here is the renderer amended to show this:

----------

  class ComboBoxRenderer extends JLabel implements ListCellRenderer
  {
    JComboBox box ;
    public ComboBoxRenderer( JComboBox box )
    {
      this.box = box ;
      setOpaque( true ) ;
      setHorizontalAlignment( CENTER ) ;
      setVerticalAlignment( CENTER ) ;
    }

    public Component getListCellRendererComponent( JList list,
                                                   Object value,
                                                   int index,
                                                   boolean isSelected,
                                                   boolean cellHasFocus )
    {
      if( index == -1 )
      {
        setText( value.toString() ) ;
      }
      else
      {
        setText( "Blah ::" + value ) ;
      }

      if( isSelected )
      {
        setBackground( list.getSelectionBackground() ) ;
        setForeground( list.getSelectionForeground() ) ;
      }
      else
      {
        setBackground( list.getBackground() ) ;
        setForeground( list.getForeground() ) ;
      }
      return this ;
    }
  }
0
 
dirkuAuthor Commented:
So, you mean since I solved the problem without Tim's help and the points should be refunded?
No, Tim gave me a good solution but I made it just a little better.
No, the combobox behaves as demanded and this question can be closed. Thank you.
0
 
VenabiliCommented:
No.. I just saw you still have troubles:) That's all. Basically the questions should be closed after they are fully resolved :)
I agree that Tim deserves the points

Venabili
0
 
TimYatesCommented:
*sniff*  I love a happy ending



;-)

Good luck dirku!!

Tim
0
 
dirkuAuthor Commented:
Me, too! 8-)

It was a good teamwork, wasn't it? You gave a good solution and I gave you a hint to make it even a littler nicer.

I'm sure I will have several question later which you can answer: I'LL BE BACK! ;-)

Dirk
0

Featured Post

Independent Software Vendors: 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!

  • 6
  • 6
  • 2
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now