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.
I would avoid the
JButton. It is perfectly possible to get the image of aJButtoninside 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
getListCellRendererComponentmethod are not contained in theJCombobox. They are only used as a stamp. That also explains why you can (and should) reuse theComponentyou return in that method, and not create new components the whole time. This is all explained in theJTabletutorial in the part about Renderers and Editors (explained for aJTablebut 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: