JTable单元格日期渲染器

时间:2014-04-30 12:12:51

标签: java swing jtable cell

尝试为日期编写自己的单元格渲染器。以此为例:

class MyRenderer extends DefaultTableCellRenderer{
    @Override
    public Component getTableCellRendererComponent(JTable jtab, Object v, boolean selected, boolean focus, int r, int c){
        JLabel rendComp = (JLabel) super.getTableCellRendererComponent(jtab, v, selected, focus, r, c);

        SimpleDateFormat formatter=new SimpleDateFormat("dd.MM.yy", Locale.ENGLISH);
        rendComp.setText(formatter.format(v));
        System.out.println(formatter.format(v));

        return rendComp;
    }
}

class DateModel extends AbstractTableModel{
    String colName[]={"Date"};
    public int getRowCount(){
        return 5;
    }

    public int getColumnCount() {
        return 1;
    }

    public String getColumnName(int c){
        return colName[c];
    }

    public Object getValueAt(int r, int c){
        return Calendar.getInstance().getTime();
    }
}

public class Test {
    public static void main(String[] args) {
        JFrame frame=new JFrame();
        frame.setSize(300, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTable table=new JTable(new DateModel());
        table.setDefaultRenderer(Date.class, new MyRenderer());

        JScrollPane pane=new JScrollPane(table);

        frame.add(pane);
        frame.setVisible(true);     

    }   
}

但我的渲染器不能正常工作,并将其返回:

enter image description here

在我自己的单元格渲染器中尝试格式化日期时,提示输出都很好。

在调试中,不要使用getTableCellRendererComponent方法。

1 个答案:

答案 0 :(得分:5)

将此方法添加到 DateModel 类:

@Override
public Class<?> getColumnClass(int columnIndex) {
    return Date.class;
}

此方法可帮助 JTable 识别您为其提供的数据类型,并将数据与相应的渲染器相关联。 JavaDoc说:

  

返回列中所有单元格值的最特定超类。 JTable使用它来为列设置默认渲染器和编辑器。

相关问题