我正在开发一个带有秋千的游戏大厅。我有一个JTable,所有不同的玩家都登录了房间,我只想在一个单元格中添加一个JComboBox。 我的问题是comboBox无法正确呈现。
我知道与此主题相关的其他话题很多,但我找不到同样问题的人。
JComboBox box = new JComboBox();
box.addItem("Warrior");
/* Adds few other items (strings)*/
this.box.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
/* sends message to server to change character when the combobox's chosen element is changed*/
}
});
TableUserModel model = new TableUserModel(localUser,this.box); //Specifying the local user as I don't want a JComboBox in the others user's rows.
JTable table = new JTable(this.model);
table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(this.box));
表模型类
public class TableUserModel extends AbstractTableModel{
private String[] columnNames = {"Username","Class","TeamColor","Action"};
private Object[][] data = {{null,null,null,null}};
private User localUser;
private JComboBox box;
public TableUserModel(User u,JComboBox box) {
this.localUser = u;
this.box = box;
}
@Override
public int getColumnCount() {
return this.columnNames.length;
}
@Override
public int getRowCount() {
return this.data.length;
}
@Override
public Object getValueAt(int row, int col) {
return this.data[row][col];
}
public String getColumnName(int col) {
return columnNames[col];
}
public Class getColumnClass(int column) {
for (int row = 0; row < getRowCount(); row++) {
Object o = getValueAt(row, column);
if (o != null) {
return o.getClass();
}
}
return Object.class;
}
//The following method updates my data array when the informations are refreshed from the server
public void refreshUsers(ArrayList<User> users) {
int elementNumber = 0;
//clears the data[][] array
this.data = new Object[][];
for (User usr : users) {
this.data[elementNumber][0] = usr.getUsername();
/*if it's the GriffinBabe's (local user) row */
this.data[elementNumber][1] = this.box; //HERE!!! I add the JComboBox into the specific cell
/*else adds a simple string information (for users other than localplayer) */
this.data[elementNumber][2] = usr.getTeamColor();
this.data[elementNumber][3] = null;
elementNumber++;
}
}
用户类别
只是一个包含一些信息的类,问题肯定不在这里
答案 0 :(得分:3)
,我只想在一个单元格中添加一个JComboBox。
这与TableModel无关。显示编辑器的是视图(即表),因此您需要自定义表。
执行此操作的一种方法是覆盖getCellEditor(...)
的{{1}}方法。例如:
JTable