Search code examples
javacalendarjavafxtableviewgregorian-calendar

javaFX show calendar value in tableview


I have the following problem. I'm making a assignment for school, we need to show a gregoriancalendar value in a tableview. this is my code for the table

TableColumn geboortedatum = new TableColumn("Geboortedatum");
    geboortedatum.setCellValueFactory(new PropertyValueFactory<Persoon, SimpleDateFormat>("gebDat"));

When I actually run this I get the following value in my tableview no matter what.

java.util.GregorianCalendar[time=-23574157200000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Berlin",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=143,lastRule=java.util.SimpleTimeZone[id=Europe/Berlin,offset=3600000,dstSavings=3600000,useDaylight=true,startyear=0,startMode=2,startMonth=2,startDay=-1,startTime=360000

and it goes on like that. anyone who has a simple solution for me? I'm probably missing something really easy here.


Solution

  • First, it looks you have the wrong type for the PropertyValueFactory. You get away with this because you are using a raw TableColumn, but your code will be easier to understand if you properly type the column. From the output, I can see that your Persoon.getGebDat() method returns a Calendar object. So you should have

    TableColumn<Persoon, Calendar> geboortedatum = new TableColumn<>("Geboortedatum");
    geboortedatum.setCellValueFactory(new PropertyValueFactory<Persoon, Calendar>("gebDat"));
    

    The default behavior of a TableCell is to call the toString method of the item it is displaying. The text you are seeing is the result of calling toString on your Calendar object.

    To change the way the data is displayed, you need to specify a cell factory on the TableColumn that creates a TableCell that knows how to format the Calendar as you want it.

    So you'll do something like

    final DateFormat dateFormat = DateFormat.getDateInstance() ; // or whatever format object you need...
    geboortedatum.setCellFactory(col -> new TableCell<Persoon, Calendar>() {
        @Override
        public void updateItem(Calendar item, boolean empty) {
            super.updateItem(item, empty);
            if (item == null) {
                setText(null);
            } else {
                setText(dateFormat.format(item.getTime()));
            }
        }
    });