Last active
January 27, 2020 21:33
-
-
Save pavelfomin/b474abf82898b0e1974fb2d5d619ed7f to your computer and use it in GitHub Desktop.
Java Swing JTable date cell editor based on JSpinner and JFormattedTextField
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.swing.*; | |
import javax.swing.table.TableCellEditor; | |
import java.awt.*; | |
import java.util.Calendar; | |
import java.util.Date; | |
/** | |
* DateCellEditor that is based on {@link JSpinner} and {@link JFormattedTextField}. | |
*/ | |
public class DateCellEditor extends AbstractCellEditor implements TableCellEditor { | |
private JSpinner spinner; | |
public DateCellEditor(String dateFormatPattern) { | |
SpinnerDateModel dateModel = new SpinnerDateModel(new Date(), null, null, Calendar.DAY_OF_MONTH); | |
spinner = new JSpinner(dateModel); | |
spinner.setEditor(new JSpinner.DateEditor(spinner, dateFormatPattern)); | |
} | |
@Override | |
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { | |
spinner.setValue(value); | |
return spinner; | |
} | |
@Override | |
public Object getCellEditorValue() { | |
return spinner.getValue(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.swing.*; | |
import javax.swing.border.LineBorder; | |
import java.awt.*; | |
import java.text.DateFormat; | |
import java.text.ParseException; | |
/** | |
* DateCellEditor that is based on {@link JFormattedTextField}. | |
*/ | |
public class DateCellTextEditor extends DefaultCellEditor { | |
/** | |
* Creates new instance of the DateCellEditor. | |
* @param format date format (set lenient to false to force date validation) | |
*/ | |
public DateCellTextEditor(DateFormat format) { | |
super(new JFormattedTextField(format)); | |
JFormattedTextField component = (JFormattedTextField) getComponent(); | |
//override the protected delegate | |
delegate = new EditorDelegate() { | |
@Override | |
public void setValue(Object value) { | |
component.setBorder(new LineBorder(Color.black)); | |
component.setValue(value); | |
} | |
@Override | |
public boolean stopCellEditing() { | |
try { | |
component.commitEdit(); | |
super.stopCellEditing(); | |
return true; | |
} catch (ParseException e) { | |
component.setBorder(new LineBorder(Color.red)); | |
return false; | |
} | |
} | |
@Override | |
public Object getCellEditorValue() { | |
return component.getValue(); | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment