3

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.

4

2 回答 2

9

首先,DefaultComboBoxModel 的构造函数可以带一个数组,但是数组中不存在属性名称,所以你不能这样做。您必须修改对象或组合框以显示对象的正确属性。

jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(things[]));

你有几个选择:)

  1. 快速轻松地覆盖 toString 以返回名称(假设 Objects 是您的类)
  2. 创建一个在其 toString() 方法中返回对象名称的包装类 (ObjectsWrapper)
  3. 以某种方式修改 JComboBox,无论是模型还是渲染器以显示所需的属性
于 2010-10-13T18:26:45.420 回答
1

不只是在您的对象上实现 a以使用默认的组合框模型toString()返回它们的属性吗?.name

请参阅类似的问题:Java Swing: E​​xtend DefaultComboBoxModel and override methods

于 2010-10-13T18:16:09.103 回答