所以我的代码遇到了问题。
首先,我有一个ArrayList
添加了对象:
cellRoomObjects = new ArrayList<>();
RoomObjects door = new RoomObjects("Door" , 1 , true);
RoomObjects oilLamp = new RoomObjects("Oil lamp", 2 , true);
RoomObjects chest = new RoomObjects("Chest" , 3 , true);
RoomObjects wallCarving = new RoomObjects("Wall Carving", 4 , false);
cellRoomObjects.add(door);
cellRoomObjects.add(oilLamp);
cellRoomObjects.add(chest);
cellRoomObjects.add(wallCarving);
其次,我得到一个JComboBox
,它将String[]
数组作为输入:
String[] objectStrings = { "Bookcase", "Chest", "Door", "Safe",
"Comfortable chair" };
JComboBox objectList = new JComboBox(objectStrings);
现在我希望我的JComboBox
显示我{{1}的每个对象的名称("Door"
,"Oil Lamp"
,"Chest"
和"Wall Carving"
)字符串,
但我不知道该怎么做。有什么建议吗?
答案 0 :(得分:2)
制作
cellRoomObjects = new Vector();
覆盖RoomObjects的toString()方法,只返回名称(或标题或任何字符串字段)
创建JComboBox(cellRoomObjects);
答案 1 :(得分:0)
您需要做的是获取每个字符串并将它们存储在数组中: 例如:
String[] myNames=new String[cellRoomObjects.size()];
int i= 0;
for(RoomObjects r : cellRoomObjects ){
myName[i]=r.getName() //assuming there is a method that gets name in RoomObjects that returns the string u want
i++
}
答案 2 :(得分:0)
我只是喜欢命名变量,你可以重命名,
public class CellRoomObject {
String itemName;
int itemNumber;
boolean ok;
public CellRoomObject(String itemName, int itemNumber, boolean ok) {
this.itemName = itemName;
this.itemNumber = itemNumber;
this.ok = ok;
}
@Override
public String toString() {
return this.itemName;
}
}
现在你的ArrayList
// create a JCOMBOBOx named say myCombobox
公共类MyFrame扩展了JFrame {
public MyFrame() {
setTitle("example");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JComboBox myBox=new JComboBox();
ArrayList<CellRoomObject> cellRoomObjects =new ArrayList<CellRoomObject>();
CellRoomObject c1=new CellRoomObject("Door" , 1 , true);
CellRoomObject c2=new CellRoomObject("Oil lamp", 2 , true);
CellRoomObject c3=new CellRoomObject("Chest" , 3 , true);
cellRoomObjects.add(c1);
cellRoomObjects.add(c2);
cellRoomObjects.add(c3);
DefaultComboBoxModel dcbm =new DefaultComboBoxModel(cellRoomObjects.toArray());
myBox.setModel(dcbm);
this.add(myBox);
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
MyFrame ex = new MyFrame();
ex.setVisible(true);
}
});
}
}
试试这个(做必要的进口)