Solved

Display a different value than selected in JComboBox

Posted on 2004-08-19
19
659 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
  • 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
 

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 50 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Passing list of object to Oracle Database Procedure 3 59
JDeveloper 12c for 32 bit 4 68
egit plugin on eclipse 8 31
tomcat not starting 6 26
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

914 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now