?
Solved

Display a different value than selected in JComboBox

Posted on 2004-08-19
19
Medium Priority
?
703 Views
Last Modified: 2012-06-21
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
Comment
Question by:dirku
[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
  • 6
  • 6
  • 2
  • +3
19 Comments
 
LVL 35

Expert Comment

by:girionis
ID: 11841059
You can get the substring of it, if "s" is the whole String '002 | Mr. Collins' try

s = s.substring(5, s.length())
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11841091
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 11841097
Just override the toString method of the item ini question to return only the name and not the number
0
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!

 

Author Comment

by:dirku
ID: 11841483
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 11841567
Tim's way is the 'correct' way
0
 
LVL 3

Expert Comment

by:JohnnyAffa
ID: 11841642
what about using JTable instead?
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11841666
So what you want is a different renderer for the editor bit of the combo as opposed to the drop down bit?
0
 

Author Comment

by:dirku
ID: 11841744
Yes, Tim. That's what I need.
0
 
LVL 35

Accepted Solution

by:
TimYates earned 200 total points
ID: 11841889
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
 

Author Comment

by:dirku
ID: 11842020
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
 
LVL 35

Expert Comment

by:TimYates
ID: 11842968
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
 

Author Comment

by:dirku
ID: 11885016
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
 
LVL 20

Expert Comment

by:Venabili
ID: 11889885
dirku,

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

Venabili
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11890031
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
 

Author Comment

by:dirku
ID: 11890121
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
 
LVL 20

Expert Comment

by:Venabili
ID: 11890135
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
 
LVL 35

Expert Comment

by:TimYates
ID: 11890370
*sniff*  I love a happy ending



;-)

Good luck dirku!!

Tim
0
 

Author Comment

by:dirku
ID: 11890479
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

Industry Leaders: 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!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month8 days, 22 hours left to enroll

765 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