Solved

Display a different value than selected in JComboBox

Posted on 2004-08-19
19
654 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
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
commonTwo  challenge 63 98
changeXy challenge 13 57
ArrayLists in ArrayLists/HashMaps? 4 39
maven project error 5 20
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …

707 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

16 Experts available now in Live!

Get 1:1 Help Now