I'm trying to create a DefaultCellEditor
for my JTable
's column so that I can set the start time and end time of a schedule.
However, I can't figure out why is it that when I input the time using the JSpinner
in JTable
's cell, I see the correct formatting for picking time but when I press enter or deselects the current cell, I get an entire date instead of just the time.
Here's my DefaultCellEditor
with JSpinner
.
public class ScheduleCellEditor extends DefaultCellEditor {
private final JSpinner timeSpinner;
public ScheduleCellEditor() {
super(new JTextField());
timeSpinner = new JSpinner();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 24);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date date = new Date();
SpinnerDateModel model = new SpinnerDateModel(date, null, null, Calendar.HOUR_OF_DAY);
model.setValue(calendar.getTime());
timeSpinner.setModel(model);
JSpinner.DateEditor editor = new JSpinner.DateEditor(timeSpinner, "HH:mm");
DateFormatter formatter = (DateFormatter) editor.getTextField().getFormatter();
formatter.setAllowsInvalid(false);
formatter.setOverwriteMode(true);
timeSpinner.setEditor(editor);
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
return timeSpinner;
}
@Override
public Object getCellEditorValue() {
return timeSpinner.getValue();
}
}
And here's how I set the DefaultCellEditor
to JTable
TableColumn
s
TableColumnModel columnModel = jtblSchedule.getColumnModel();
TableColumn startTimeCol = columnModel.getColumn(1);
TableColumn endTimeCol = columnModel.getColumn(2);
startTimeCol.setCellEditor(new ScheduleCellEditor());
endTimeCol.setCellEditor(new ScheduleCellEditor());
When I click the cell and pick the time, it shows correct formatting where I only see HH:mm
When I click out of the cell or click somewhere else, I get the full date even when the editor and model is formatted to time.
Do you have any suggestions on how to solve this. I just need the time to show and not the complete date.
I'll appreciate any help.
Thanks.