簡體   English   中英

JTable單元格日期渲染器

[英]JTable cell date renderer

嘗試為日期編寫自己的單元格渲染器。 以這個為例:

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);     

    }   
}

但是我的渲染器無法正常工作,並返回以下代碼:

在此處輸入圖片說明

當嘗試格式化日期,例如在我自己的單元格渲染器中進行提示時,一切正常。

在調試中不要獲取getTableCellRendererComponent方法。

將此方法添加到DateModel類中:

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

此方法有助於JTable識別您提供給它的數據類型,並將數據與對應的渲染器關聯。 JavaDoc說:

返回列中所有單元格值的最特定的超類。 JTable使用它為列設置默認的渲染器和編輯器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM