Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add a JXDatepicker for a JTable column

I'm using a JTable. There I have a Date column, where I need to make a JXDatePicker appear when I click on a cell so that I can select a date from it.

Can someone show me how to do this?

Thanks! waiting for an answer..

like image 708
Anubis Avatar asked Dec 02 '22 21:12

Anubis


2 Answers

You should probably use DatePickerCellEditor, which is a CellEditor using a JXDatePicker as editor component. For example:

TableColumn dateColumn = table.getColumnModel().getColumn(columnIndex);
dateColumn.setCellEditor(new DatePickerCellEditor());

Here is a demo table:

import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableColumn;

import org.jdesktop.swingx.table.DatePickerCellEditor;

public class DateColumnDemo {

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("DateColumnDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JTable table = new JTable(new Object[][] { { "1", new Date() } },
                new Object[] { "Id", "Time" });

        TableColumn dateColumn = table.getColumnModel().getColumn(1);
        dateColumn.setCellEditor(new DatePickerCellEditor());

        JScrollPane scrollPane = new JScrollPane(table); 

        frame.add(scrollPane);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
like image 148
tenorsax Avatar answered Dec 08 '22 01:12

tenorsax


As already mentioned in my comment to Max' correct answer:

JXTable (same as a plain JTable) does format a date value by default, using the format as returned by DateFormat.getInstance(). If the formatting appears to not work, that's typically an incomplete implementation of the tableModel: default renderer for a particular type is used only when the columnClass returns that particular type

// in your TableModel, implement getColumnClass
@Override
public Class<?> getColumnClass(int columnIndex) {
    if (columnIndex == myDateColumnIndex) {
        return Date.class;
    }
    ...
}

To install a date renderer with a custom format, instantiate a DefaultTableRenderer with a FormatStringValue as appropriate and tell the table to use it (either per-column, works with whatever columnClass or per-table, works for columns returning the Date class)

StringValue sv = new FormatStringValue(new SimpleDateForma("dd-MMMM-yyyy"));
TableCellRenderer r = new DefaultTableRenderer(sv);
// either per-column
table.getColumn(dateColumnIndex).setCellRenderer(r);
// or per-table
table.setDefaultRenderer(Date.class, r);
like image 30
kleopatra Avatar answered Dec 08 '22 01:12

kleopatra