Question

Try to write own cell renderer for date. Make this for example:

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

    }   
}

But my renderer dont work fine, and return this:

enter image description here

When try format date like in my own cell renderer for prompt output all fine.

In debug do not get to getTableCellRendererComponent method.

Était-ce utile?

La solution

Add this method to your DateModel class:

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

This method helps JTable to recognize what type of data you give to it and associate data with correspond renderer. JavaDoc says:

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top