Setting the date format in JXTable cell

倖福魔咒の 提交于 2021-01-29 07:39:51

问题


On this thread I've figured out how to add a JXDatePicker in to a JXTable (or JTable) cell. But I've a small issue now.

DatePicker pops up and works fine according to my need. But I can't change the display format of the date in the cell. It shows in the following long format.

Eg: Wed Aug 01 00:00:00 IST 2012

But I need it in dd-MMM-yyyy format.

I've tried changing the DatePickerCellEditor's format. It partly works. Which means, now it shows the date according to the set format when that cell is in focus. But when I focus on some other cell, it again goes back to the above format.

May be the fault is not with the DatePickerCellEditor, may be it has to do something with the tableModel. But can't figure it out. Any help is appreciated..

Thanks!


回答1:


As per you're previous question, the process it pretty much the same, except you want to use renderer instead of an editor

public class DateCellRenderer extends DefaultTableCellRenderer {

    @Override
    public Component getTableCellRendererComponent(JTable jtable, Object value, boolean selected, boolean hasFocus, int row, int column) {

        if (value instanceof Date) {

            // You could use SimpleDateFormatter instead
            value = DateFormat.getDateInstance().format(value);

        }


        return super.getTableCellRendererComponent(jtable, value, selected, hasFocus, row, column);

    }

Then, to apply the render you can either apply it to specific column (so only that column will use it), or in the case of something like Date you might want to use it for all columns using the Date value...

JTable table = new JTable();

DateCellRenderer renderer = new DateCellRenderer();
// Apply for a single column
table.getColumnModel().getColumn(0).setCellRenderer(renderer);
// OR apply for all columns using the Date class
table.setDefaultRenderer(Date.class, renderer);



回答2:


That is because a TableCellEditor is only used, when you really are editing a cells value. For representing a value, while not in edit-mode a TableCellRenderer is used.

I recommend reading this article to understand more about the concept of renderer and editors for tablecells.



来源:https://stackoverflow.com/questions/11823334/setting-the-date-format-in-jxtable-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!