JComboBoxes - Using setModel to access Objects (in Swing)
Quick background, I am using Netbeans to develop this (I don't have much experience with Swing and have lost points on experience at the chance to gain development speed). In Netbeans it is obviously restrictive as to what code you can modify to stop novice users breaking the code (which I have already amusingly done once) Anyway, I have a class of Objects, these Objects have a name property. Within the application I have directly initialised an array of these objects and called them "things";
Objects[] things = new Objects[2];
things[0] = new Objects("The first thing");
things[1] = new Objects("The second thing");
The contents and names are deliberately inane as this is a test to get this working (rather than pulling apart a part written program). After some research and reading I have discovered that I "should" be able to load objects into the setModel parameter using the following code;
new javax.swing.DefaultComboBoxModel(things[].name)
//The above is the code to use within setModel, the below is the completed example
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(things[].name));
This hasn't worked, and despite my best efforts to google this seems to be too specific to nail down a decent answer. The end result开发者_开发技巧 is that I would like to have; "The first thing" and "The second thing" displayed within the drop down list, and then obviously I can expand on this within the real program by referencing any other data held in that object on the screen.
Any suggestions or even pointers to help me think this out would be appreciated.
First of all, the constructor of the DefaultComboBoxModel can take an array, but the property name does not exist in an array so you cannot do that. You would have to modify your objects or the combobox to show the correct property of your object.
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(things[]));
You have several options :)
- The quick and easy override toString to return name (assuming Objects is your class)
- Create a wrapper class (ObjectsWrapper) that in its toString() method returns Objects name
- Modify the JComboBox in some way, either the model or the renderer to show the desired property
Wouldn't just implementing a toString()
on your objects to return their .name
property work with the default Combo Box model?
See the similar question: Java Swing: Extend DefaultComboBoxModel and override methods
精彩评论