1

I have a requirement in JavaFX 2 to display the notifications on the header. These notifications are populated in the database through an external system.

When a new notification is inserted in the database, my JavaFX application should listen to the same and refresh the header.

One solution I can think about is to implement a timeline that triggers the code to retrieve the latest notification status once every fixed time period, may be once every 2 mins.

Other than this, is there any other way to achieve this? Any hints on this would be highly appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sirish V
  • 930
  • 2
  • 12
  • 24

1 Answers1

2

You can create a new Task that would be listening (or checking) for changes in your database. This Task would be running in a different Thread as not to block your UI. Once a change occurs, it can then update your UI.

Your code could look like this :

//... initialize your variables.
task = new DatabaseWatcher();
executor = Executors.newSingleThreadExecutor();
executor.execute(task);

And your DatabaseWatcher :

public class DatabaseWatcher extends Task<Object> {
    public DatabaseWatcher() {
        //initialize here
    }

    @Override
    protected Object call() throws Exception {
        //Get data from database
        //if new update :
        updateUI();
        return null;
    }

    private void updateUI() {
        
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                //Set your new values in your UI
                //Call the method in your UI to update values.
            }
        });
    }
}

This should get you started on the right path.

See Also

Community
  • 1
  • 1
blo0p3r
  • 6,790
  • 8
  • 49
  • 68