我正在使用JTable
并修改其模型以包含JComboBox
个项目。我这样做:
JComboBox comboBox = new javax.swing.JComboBox(substituteNames.split(","));
comboBox.setSelectedIndex(0);
editors.add(new javax.swing.DefaultCellEditor(comboBox));
例如,其中,substituteNames为“1,2,3,4”。
但是,在我的JTable
初期,JComboBox
元素'所选项目为空,但JComboBox
中没有空元素。选择其他内容后,空元素消失。为什么会发生这种情况,我如何解决我JComboBox
的所选项目最初是第一个元素?
编辑: 这就是我编辑表模型的方式。
RowEditorModel rm = new RowEditorModel();
issue.setRowEditorModel(rm);
for (int issueIndex = 0; issueIndex < rowIndexes.size(); issueIndex++)
{
rm.addEditorForRow(rowIndexes.get(issueIndex).intValue(), editors.get(issueIndex));
}
RowEditorModel是一个类:
public class RowEditorModel
{
private Hashtable data;
public RowEditorModel()
{
data = new Hashtable();
}
public void addEditorForRow(int row, TableCellEditor e )
{
data.put(new Integer(row), e);
}
public void removeEditorForRow(int row)
{
data.remove(new Integer(row));
}
public TableCellEditor getEditor(int row)
{
return (TableCellEditor)data.get(new Integer(row));
}
}
问题是JTableX类型,它是JTable的传递后代:
public class JTableX extends MiniTable
{
private boolean[][] editable_cells = null; // 2d array to represent rows and columns
@Override
public boolean isCellEditable(int row, int col) { // custom isCellEditable function
if (editable_cells == null)
{
editable_cells = new boolean[getModel().getRowCount()][getModel().getColumnCount()];
}
return this.editable_cells[row][col];
}
public void setCellEditable(int row, int col, boolean value) {
if (editable_cells == null)
{
editable_cells = new boolean[getModel().getRowCount()][getModel().getColumnCount()];
}
this.editable_cells[row][col] = value; // set cell true/false
((DefaultTableModel)getModel()).fireTableCellUpdated(row, col);
}
protected RowEditorModel rm;
public JTableX()
{
super();
rm = null;
}
public JTableX(TableModel tm)
{
super(tm);
rm = null;
}
public JTableX(TableModel tm, TableColumnModel cm)
{
super(tm,cm);
rm = null;
}
public JTableX(TableModel tm, TableColumnModel cm, ListSelectionModel sm)
{
super(tm,cm,sm);
rm = null;
}
public JTableX(int rows, int cols)
{
super(rows,cols);
rm = null;
}
public JTableX(final Vector rowData, final Vector columnNames)
{
super(rowData, columnNames);
rm = null;
}
public JTableX(final Object[][] rowData, final Object[] colNames)
{
super(rowData, colNames);
rm = null;
}
// new constructor
public JTableX(TableModel tm, RowEditorModel rm)
{
super(tm,null,null);
this.rm = rm;
}
public void setRowEditorModel(RowEditorModel rm)
{
this.rm = rm;
}
public RowEditorModel getRowEditorModel()
{
return rm;
}
public TableCellEditor getCellEditor(int row, int col)
{
TableCellEditor tmpEditor = null;
if (rm!=null)
tmpEditor = rm.getEditor(row);
if (tmpEditor!=null)
return tmpEditor;
return super.getCellEditor(row,col);
}
}
答案 0 :(得分:4)
您不能只设置组合框的索引,因为该列中的所有行都使用相同的编辑器。
因此,当您编辑JTable中使用编辑框的编辑框中的单元格时,组合框的选定项目将设置为当前正在编辑的单元格的TableModel中包含的值。
我怎么能解决我的JComboBox的选定项目最初是第一个元素?
您需要更新所有单元格的TableModel以包含该值。
阅读Using a ComboBox as an Editor上Swing教程中的部分,以获取一个工作示例。请注意TableModel如何为每行包含不同的值。