java - Implement a blocking call in Swing, simulating modality -


as follow-up question "javafx filechooser in swing", have answered, wonder if there's possibility simulate modal blocking call in swing in more elegant way. here's relevant code:

// trick emulate modality: final jdialog modalblocker = new jdialog(); modalblocker.setmodal(true); modalblocker.setundecorated(true); modalblocker.setopacity(0.0f); final countdownlatch modalitylatch = new countdownlatch(1); final futuretask<t> task = new futuretask<t>(() -> {     // <-- code checking whether task cancelled     // , notifying started     try {         return callable.call();     } {         // wait until swing thread blocked in setvisible():         modalitylatch.await();         // , unblock it:         swingutilities.invokelater(()                 -> modalblocker.setvisible(false));     } }); // run task in javafx thread: platform.runlater(task); // <-- code waiting until task started, // canceling if it's not // trick notify task after have been blocked // in setvisible(): swingutilities.invokelater(() -> {     // notify ready result:     modalitylatch.countdown(); }); modalblocker.setvisible(true); // blocks modalblocker.dispose(); // release resources try {     return task.get(); } catch (executionexception ex) {     // exception handling } 

the idea here keep swing updating, repainting, moving progress bars , doing other visual tasks while blocking user input, until blocking call returns. if did simple return task.get() without modality mess, swing freeze while task working, not catastrophic, still undesirable.

the whole thing seems working perfectly, @ least under windows 7, "seems working perfectly" not in line "write once, run everywhere", it?

i have tried in jdialog/dialog source code figure out how modality blocks without totally freezing gui, alas code complicated, , worse, uses many private features prevent me doing in code if figured out how it's working.

the question is: maybe there's more elegant way have missed? need perform blocking call keeps gui updating, blocks user input until call returns.


Comments