我有一个约有17列的JTable。对于其中一些列,我想要ComboBoxes,对于其他人,我不会。一些代码:
public final JTable table;
void setCellEditors(){
setBooleanCellEditor (table); // comboBox for boolean values
setIntCellEditor (table); // comboBox for int values
setTypeCellEditor (table);
setAnotherTypeCellEditor (table);
// .. and so on, for all types I need comboboxes
}
大多数类型的cellEditor函数如下所示:
private void setTypeCellEditor (JTable jt) {
DefaultCellEditor dce = new DefaultCellEditor (Type.buildComboBox ());
jt.setDefaultEditor (Type.class, dce);
}
这样可以正常工作,因为该类型对于该表是唯一的,换句话说,我只有一个类型为Boolean的列,一个具有Int,一个具有AnotherType等。现在的问题是两列具有String值,但需要不同的ComboBoxes。意思是,上面的代码不起作用,因为它们都是String.class。
当然,我尝试通过说&#34来解决这个问题;在第10列我想要这个ComboBox":
private void setYetAnotherTypeCellEditor (JTable jt) {
DefaultCellEditor dce = new DefaultCellEditor (YetAnotherType.buildComboBox ());
if (jt.getColumnModel ().getColumnCount() > 0) {
jt.getColumnModel ().getColumn (9).setCellEditor (dce);
}
}
然而,这似乎不起作用,我不知道为什么。我也试过this guide,但这没有用。基本上,我认为setCellEditor由于某种原因没有设置单元格编辑器。
很难更具体,因为这背后有很多代码。
答案 0 :(得分:3)
很难更具体,因为这背后有很多代码。
Using a Combo Box as an Editor说明了按列设置单元格编辑器。如下所示的Minimal, Complete, and Verifiable example将允许您单独研究问题。
import java.awt.EventQueue;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
/**
* @see https://stackoverflow.com/a/37435196/230513
*/
public class Test {
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable table = new JTable(1, 2);
table.getColumnModel().getColumn(0).setCellEditor(Type1.buildComboBox());
table.getColumnModel().getColumn(1).setCellEditor(Type2.buildComboBox());
f.add(new JScrollPane(table));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static class Type1 {
private static TableCellEditor buildComboBox() {
return new DefaultCellEditor(new JComboBox(
new DefaultComboBoxModel<>(new String[]{"A", "B", "C"})));
}
}
private static class Type2 {
private static TableCellEditor buildComboBox() {
return new DefaultCellEditor(new JComboBox(
new DefaultComboBoxModel<>(new String[]{"X", "Y", "Z"})));
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Test()::display);
}
}
答案 1 :(得分:1)
我不知道你在哪里初始化JTable
名为table
的地方,而且我也不知道JTable
传递给setYetAnotherTypeCellEditor()
的位置是什么{1}}作为名为jt
的参数。我猜测jt
不是null
;但是没有任何列,jt.getColumnModel().getColumnCount() > 0
可能是false
。尝试
private void setYetAnotherTypeCellEditor (JTable jt) {
DefaultCellEditor dce = new DefaultCellEditor (YetAnotherType.buildComboBox());
jt.getColumnModel ().getColumn (9).setCellEditor (dce);
}