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..
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();
}
});
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With