我正在使用此函数创建jTable
,其中一些特殊的单元格有一个jComboBox
作为编辑器:
void fillTable_(){
final JComboBox myEditor = new JComboBox(new String[] {"yes", "no", "maybe"});
String[][] data = new String[10][2];
data[0][0] = "0,0";
data[0][1] = "0,1";
data[1][0] = "1,0";
data[1][1] = "1,1";
data[2][0] = "2,0";
data[2][1] = "2,1";
String[] columnNames = {"Nom", "Valeur"};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
jTable1 = new JTable(model){
DefaultCellEditor myCellEditor = new DefaultCellEditor(myEditor);
@Override
public TableCellEditor getCellEditor(int row, int column){
int modelColumn = convertColumnIndexToModel(column);
int modelRow = convertRowIndexToModel(row);
if(modelColumn == 1 && modelRow == 1){
return myCellEditor;
} else {
return super.getCellEditor(row, column);
}
}
};
}
但是jTable保持空甚至不是纯文本显示。有什么不对吗?
答案 0 :(得分:3)
但是
JTable
仍然是空的;甚至不显示纯文本。
您需要一个与您的编辑器对应的渲染器,正如此example中建议的那样,其中包含ValueRenderer
和 a ValueEditor
。
我只需要在
的某些单元格中添加JComboBox
JTable
如How to Use Tables: Concepts: Editors and Renderers中所述,“单个单元格渲染器通常用于绘制包含相同类型数据的所有单元格。”
我指定了行和列,但没有发生任何事情
当我将新JTable
添加到容器时,您的代码似乎有用。
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
/** @see http://stackoverflow.com/questions/7200500 */
public class TableTest extends JPanel {
public TableTest() {
this.setPreferredSize(new Dimension(320, 240));
final JComboBox myEditor = new JComboBox(
new String[]{"yes", "no", "maybe"});
String[][] data = new String[10][4];
data[0][0] = "0,0";
data[0][5] = "0,1";
data[1][0] = "1,0";
data[1][6] = "1,1";
data[2][0] = "2,0";
data[2][7] = "2,1";
String[] columnNames = {"Nom", "Valeur"};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model) {
DefaultCellEditor myCellEditor = new DefaultCellEditor(myEditor);
@Override
public TableCellEditor getCellEditor(int row, int column) {
int modelColumn = convertColumnIndexToModel(column);
int modelRow = convertRowIndexToModel(row);
if (modelColumn == 1 && modelRow == 1) {
return myCellEditor;
} else {
return super.getCellEditor(row, column);
}
}
};
this.add(table);
}
private void display() {
JFrame f = new JFrame("TableTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new TableTest().display();
}
});
}
}
答案 1 :(得分:2)
1)创建JTable,TableModel,JComboBox,然后将其与官方教程中的example放在一起
2)对于布尔组件,不需要创建自己的TableCellEditor,默认情况下为JTable 在TableCell中支持String,Integer,Double,Boolean,Date和Icon/ImageIcont
中的a.m .... here,here的另一个示例