TableColumn and ObservableValue

Today I learned a couple of things that they don’t tell you in the official documentation or on Stack Overflow. If you want to display some information in a table and that information updates and you want to display those updates, then you have to hook things up the hard way, and not the way everyone tells you to do it.

Let’s say you want to show a list of mailboxes and for each mailbox, the total number of messages currently in the box and the total number of messages received during the life of the server process. If you follow the pattern of examples on the web, then you’ll wind up with either an empty table (if you use PropertyValueFactory and name the getters like ‘getMessageCountProperty’ and you instantiate the factory with a string like ‘messageCount’) or a table that has the correct initial values but which doesn’t update (if you use PropertyValueFactory and return the actual Integer for the count and name the getter ‘getMessageCount’) or you get a table that just lists the message count as “SimpleIntegerProperty” if you try returning the property from a getter named ‘getMessageCount’.

The right way to do it is to have the bean method return an ObservableValue (which, interestingly, needs to be ObservableValue<Number> and not ObservableValue<Integer> never mind that it’s a SimpleIntegerProperty). Don’t use a PropertyValueFactory; instead, do it the long way (which is made significantly shorter with Java 7’s lambda notation). Here’s a gist which shows how it’s done.

Published by pirateguillermo

I play the bagpipes. I program computers. I support my family in their various endeavors, and I enjoy my wonderful life.

Leave a Reply

Discover more from Mechadarwin

Subscribe now to keep reading and get access to the full archive.

Continue reading