Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTable define an editor for LocalTime type

Tags:

java

swing

I am using Java 8, after following documentation:

  • How to Use Tables - Using an Editor to Validate User-Entered Text

I'd like to setup a specialized formatter when editing a column in my JTable. This column contains java.time.LocalTime instances.

JTable table;
...
table.setDefaultEditor(LocalTime.class, new LocalTimeEditor());

Where LocalTimeEditor is defined by (tentatively):

public class LocalTimeEditor extends DefaultCellEditor {
    JFormattedTextField ftf;

  public LocalTimeEditor() {
    super(new JFormattedTextField());
    ftf = (JFormattedTextField) getComponent();

    // Set up the editor for the LocalTime cells.
    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
    ftf.setFormatterFactory(new DefaultFormatterFactory(dateFormatter));

But this leads to the following compilation error:

The constructor DefaultFormatterFactory(DateTimeFormatter) is undefined

I'd like to stay away from a solution involving SimpleDateFormat (+DateFormatter) as explained here or here, since java.util.Date should be considered legacy (see old code here).

Is there a solution to integrate DateTimeFormatter with JFormattedTextField, or am I blocked by:

  • JDK-8034818 - JFormattedTextField does not accept DateTimeFormatter as formatter

I'd also like to stay away from MaskFormatter, since it does not allow easy error handling for something like: "25:70:90".

like image 589
malat Avatar asked Dec 20 '17 10:12

malat


People also ask

How to use JTable in Java swing?

JTable(): A table is created with empty cells. JTable(int rows, int cols): Creates a table of size rows * cols. JTable(Object[][] data, Object []Column): A table is created with the specified name where []Column defines the column names.


1 Answers

As per the argument of DefaultFormatterFactor, I created a new JFormattedTextField.AbstractFormatter

class JTFormater extends JFormattedTextField.AbstractFormatter{
    final DateTimeFormatter formatter;
    public JTFormater(DateTimeFormatter formatter){
        this.formatter =  formatter;
    }
    @Override
    public Object stringToValue(String text) throws ParseException {
        return formatter.parse(text);
    }

    @Override
    public String valueToString(Object value) throws ParseException {
        if(value instanceof TemporalAccessor){
            return formatter.format((TemporalAccessor) value);
        } else{
            throw new ParseException("not a valid type at", 0);
        }
    }
}

From this I could parse and display LocalTime's, although in my implementation it is pretty clumsy.

like image 98
matt Avatar answered Sep 28 '22 05:09

matt