我正在使用NetBeans 8.0在Java中开发桌面应用程序 有一个带有自定义表模型的JTable。但是我能够 使用Date数据类型编辑列。
以下是代码段。
public class DuesTableModel extends AbstractTableModel implements TableModelListener {
private List<List<Object>> dataList = new ArrayList<>();
private String[] header = { "ID"," PAYMENT YEAR" , "AMOUNT"}; // Payment year is a date
datatype
private int minRowCount = 5;
public DuesTableModel()
{ super(); }
public List<List<Object>> getDataList() {
return dataList;
}
public void setDataList(List<List<Object>> dataList) {
this.dataList = dataList;
fireTableDataChanged();
fireTableStructureChanged();
}
@Override
public int getRowCount() {
return Math.max(minRowCount, dataList.size());
}
@Override
public int getColumnCount() {
return header.length;
}
public void setHeader(String[] header) {
this.header = header;
}
public String[] getHeader() {
return header;
}
@Override
public void setValueAt(Object value, int row, int col)
{
int x = 0;
for(List<Object> l : dataList)
{
if(x == row)
{ l.set(col, value);}
x++;
}
fireTableCellUpdated(row,col);
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object value = null;
if(rowIndex < dataList.size())
{value = dataList.get(rowIndex).get(columnIndex);}
return value;
}
@Override
public String getColumnName(int col) {
return header[col];
}
@Override
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;
}
@Override
public boolean isCellEditable(int row, int col) {
return true; //col
}
@Override
public void tableChanged(TableModelEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
将isCellEditable方法设置为true后,其他列中的单元格现在可以编辑,但“付款年”列是日期数据类型。
欢迎任何建议。
答案 0 :(得分:1)
我建议您使用DefaultTableModel
代替AbstractTableModel
并使用TableCellRenderer
将日期列格式化为yyyy
以仅显示年份。
示例代码:
final String[] header = { "ID", " PAYMENT YEAR", "AMOUNT" };
final Object[][] data = { { "1", new Date(), 500 }, { "2", new Date(), 200 },};
final DefaultTableModel model = new DefaultTableModel(data, header);
final JTable table = new JTable(model) {
@Override
public Class<?> getColumnClass(int column) {
switch (column) {
case 1:
return Integer.class;
case 2:
return Date.class;
default:
return String.class;
}
}
@Override
public boolean isCellEditable(int row, int col) {
return true;
}
};
TableCellRenderer tableCellRenderer = new DefaultTableCellRenderer() {
SimpleDateFormat f = new SimpleDateFormat("yyyy");
public java.awt.Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
if( value instanceof Date) {
value = f.format(value);
}
return super.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
}
};
table.getColumnModel().getColumn(1).setCellRenderer(tableCellRenderer);
了解更多...