I would like to put a JButton inside a JComboBox. This button lets users browse for files. The file the user selects gets added to the JComboBox list. How do I do this? Do I use some kind of a Renderer? Thank you.
EDIT: After reading more about ListCellRenderer I tried the following code:
JComboBox comboBox = new JComboBox(new String[]{"", "Item1", "Item2"});
ComboBoxRenderer renderer = new ComboBoxRenderer();
comboBox.setRenderer(renderer);
class ComboBoxRenderer implements ListCellRenderer {
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
JButton jbutton = new JButton("Browse");
return jbutton;
}
}
The problem with the above is that the Button "Browse" will be added 3 times and I want it to display only once and below it to display Item1 and Item2 as normal/regular combobox selection objects.
Indeed, you will have to use a custom renderer as explained on http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#renderer.
Depending on where you want to put the search button, you could take a look at the xswingx Prompt/Buddy API. You could use this to "buddy" the browse button with the editor field
Or you could simply add a browse button next to the combo box.
After trying out many things I think I figured out the Answer, I am sure it will look very easy when you see it:
You can now customize the button and labels any way you wish.
I would avoid the
JButton
. It is perfectly possible to get the image of aJButton
inside your combobox, but it will not behave itself as a button. You cannot click it, it never gets visually 'pressed' nor 'released', ... . In short, your combobox will contain an item which behaves unfamiliar to your users.The reason for this is that the components you return in the
getListCellRendererComponent
method are not contained in theJCombobox
. They are only used as a stamp. That also explains why you can (and should) reuse theComponent
you return in that method, and not create new components the whole time. This is all explained in theJTable
tutorial in the part about Renderers and Editors (explained for aJTable
but valid for all other Swing components which use renderers and editors).If you really want an item in the combobox that allows to show a file chooser, I would opt for something similar to the following SSCCE: