我想在JTable中显示Combobox。对于JTable,我使用TableModel。我已经成功地展示了Combobox(不是它的toString())。问题是我无法查看其内容。组合框必须是不可编辑的。我已经阅读了很多教程,但是我还没有找到TableModel。我发现这个代码:ComboBox未在JTable中显示其内容
JComboBox comboBox = new JComboBox();
comboBox.addItem("Snowboarding");
comboBox.addItem("Rowing");
comboBox.addItem("Knitting");
comboBox.addItem("Speed reading");
comboBox.addItem("Pool");
comboBox.addItem("None of the above");
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
//Set up tool tips for the sport cells.
DefaultTableCellRenderer renderer =
new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
sportColumn.setCellRenderer(renderer);
}
我不能使用它有两个原因。我的Combobox的内容是不一样的,他们不使用TableModel。这里是我的代码:
公共类TProfModel扩展的DefaultTableModel实现TableModel的{
/**
*
*/
private static final long serialVersionUID = 1L;
private String[] names = { "Nom", "Prénom", "Matière", "Classes" };
private Model model;
public TProfModel(Model model){
this.model = model;
fireTableDataChanged();
}
public Class<?> getColumnClass(int col) {
return getValueAt(0,col).getClass();
}
public int getColumnCount() {
return names.length;
}
public String getColumnName(int col) {
return names[col];
}
public int getRowCount() {
if(model != null)
return model.getProfs().size();
return 0;
}
public Object getValueAt(int line, int col) {
switch (col) {
case 0:
return model.getProfs().get(line).getNom();
case 1:
return model.getProfs().get(line).getPrenom();
case 2:
return model.getProfs().get(line).getMatiere();
case 3:
return getClasses(line);
}
return null;
}
private JComboBox<String> getClasses(int line) {
JComboBox<String> comboBox = new JComboBox<String>();
for(String classe : model.getProfs().get(line).getClasses())
comboBox.addItem(classe);
comboBox.setSelectedIndex(0);
return comboBox;
}
public boolean isCellEditable(int arg0, int arg1) {
if(arg1 == 3)
return false;
return true;
}
public void removeTableModelListener(TableModelListener arg0) {
// TODO Auto-generated method stub
}
@Override
public void setValueAt(Object object, int line, int col) {
switch (col) {
case 0:
model.getProfs().get(line).setNom((String) object);
break;
case 1:
model.getProfs().get(line).setPrenom((String) object);
break;
case 2:
model.getProfs().get(line).setMatiere((String) object);
}
model.writeData();
}
}
不要从模型中返回组件。编辑器和渲染器的责任是解释如何最好地显示来自型号 – MadProgrammer
的提供的值以及如何做到这一点?我创建了一个实现TableCellRenderer的类,但我不知道如何使用它。 – Hunsu
返回该列的给定行的值作为编辑器在对其调用setSelectedValue时可以使用的对象,在这种情况下,这将是一个“String”值... – MadProgrammer