I use DatePickerCellEditor in JTable columns.
Now when i want to get value and convert it to date get some exceptions in this part:
Date date = new Date(valueAt);
.
And get this Exception:
java.lang.IllegalArgumentException
at java.util.Date.parse(Date.java:617)
at java.util.Date.<init>(Date.java:274)
Here is my code.
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()}, {"2", new
Date()}}, new Object[]{"Id", "Time"});
TableColumn dateColumn = table.getColumnModel().getColumn(1);
dateColumn.setCellEditor(new DatePickerCellEditor());
JPanel jp = new JPanel(new FlowLayout());
JScrollPane scrollPane = new JScrollPane(table);
JButton jb = new JButton("Button");
jb.addActionListener(e -> {
String valueAt = table.getValueAt(0, 1).toString();
try {
Date date = new Date(valueAt);
} catch (Exception ee) {
ee.printStackTrace();
}
System.out.println(table.getValueAt(0, 1));
System.out.println(table.getValueAt(1, 1));
});
jp.add(scrollPane);
jp.add(jb);
frame.add(jp);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
createAndShowGUI();
}
}
Please help me. thanks
Your JTable holds Date objects in the first column:
JTable table = new JTable(new Object[][]{
{"1", new Date()},
{"2", new Date()}
}, new Object[]{"Id", "Time"});
And so this:
String valueAt = table.getValueAt(0, 1).toString();
followed by
Date date = new Date(valueAt);
Where you call toString()
and then creating a new Date with the String representation makes no sense. Instead cast the Object to java.util.Date
.
Date date = (Date) table.getValueAt(0, 1);
Although you may wish to first do a null
check before using such objects.