0

I have a combobox with list of authors and with change in combobox I have to show the author's detail in table using java swing. I did like:

for(Author author: Application.authors){
    jComboBoxAuthors.addItem(author);
}

and with change in item selected :

if(jComboBoxAuthors.getSelectedIndex()>0){
    Author author = (Author)e.getItem();
    String name = author.getFirstName()+" "+author.getLastName();
}

It shows object in combo but i need the name only and if I dojComboBoxAuthors.addItem(author.getFirstName()); I can't get value in table ie. name return nothing. How can I fix this issue?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Agnosco
  • 155
  • 2
  • 11
  • 2
    Use a [*Custom Renderer*](http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer), for [example](http://stackoverflow.com/a/10951919/230513). – trashgod Dec 21 '14 at 02:11
  • I think you might like to take a look at [How to Use Combo Boxes](http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html) and [Writing a Custom Cell Renderer](http://docs.oracle.com/javase/tutorial/uiswing/components/list.html#renderer) – MadProgrammer Dec 21 '14 at 02:41

2 Answers2

0

Using a custom renderer will break the default functionality of a JComboBox. That is you will no longer be able to select an item using the keyboard.

Check out Combo Box With Custom Renderer for more information and a more complete solution that shows how to fix this problem.

camickr
  • 321,443
  • 19
  • 166
  • 288
0

One thing you can do is override the toString() method as following

@Override
    public String toString() {
        return firstName+" "+lastName; // so that name will be displayed instead of default object
    }

But it has its limitations. Hope it helps

asok Buzz
  • 1,876
  • 3
  • 24
  • 50