java - JTable 单元格日期呈现器

标签 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 方法。

最佳答案

将此方法添加到您的 DateModel 类中:

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

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

Returns the most specific superclass for all the cell values in the column. This is used by the JTable to set up a default renderer and editor for the column.

关于java - JTable 单元格日期呈现器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23387790/

相关文章:

java - 在 JFrame 或 JPanel 中加载 javascript

java - 获取列和行选择时数组越界?

java - 如何在 Android 上显示 GoogleMap v2

java - JXDatePicker swingx语言

java - 如何强制 Java 编译器只编译我指定的源文件?

java - 如何使用 Hibernate 保留枚举类型字段?

java - 鼠标监听器不工作

java - 可滚动的流程面板

java - 如何: JTable look and feel like Windows 7 Details View or Vuze table

java - JTable 复选框应在选中时启动计时器