JavaFX: Capture screen focused event - event-handling

Is there a way to capture the event when a stage or screen gets focus? I tried to use focusedProperty but I guess that is used only when initially the stage/screen gets shown.
I am not sure if essentially I have to capture, WindowEvent.WINDOW_SHOWN event. I did try the following piece of code in my application, but there is probably a mistake.
stage.addEventFilter(WindowEvent.WINDOW_SHOWN, new EventHandler<WindowEvent>()
{
#Override
public void handle(WindowEvent window)
{
System.out.println("EventFilter :: Window shown");
}
});
stage.addEventHandler(WindowEvent.WINDOW_SHOWN, new EventHandler<WindowEvent>()
{
#Override
public void handle(WindowEvent window)
{
System.out.println("EventHandler :: Window shown");
}
});
None of the sysouts is shown when I execute the program.
Another part to the same problem is whether the event handler would get triggered if lets say I minimize and maximize the application(i.e the application again got focus) or I lock my machine and unlock it?

Related

Is it possible/how to display a message on the FeedbackPanel more than one time

I have a org.apache.wicket.markup.html.panel.FeedbackPanel in my panelA class. The feedback panel is instantiated in a panelA constructor with one message to display -> feedbackPanel.info("displayFirstTime"). I am navigating to a new page and later to the previous panelA with a command
target.getPage().get(BasePage.CONTENT_PANEL_ID).replaceWith(panelA);
but the message "displayFirstTime" won't be displayed on the feedback panel again.
I have made it with overriding a panel onBeforeRender method
#Override
public void onBeforeRender() {
super.onBeforeRender();
if (again_displayCondition) {
this.info("displayFirstTime");
}
}
but it's not a clean solution.
Is it possible or how to make it, that when moving to a panelA page for the 2nd time the feedback message will be also displayed ?
Wicket uses application.getApplicationSettings().getFeedbackMessageCleanupFilter() to delete the feedback messages at the end of the request cycle.
By default it will delete all already rendered messages.
You can setup a custom cleanup filter that may leave some of the messages, e.g. if they implement some interface. For example:
component.info(new DoNotDeleteMe("The actual message here."));
and your filter will have to check:
#Override
public boolean accept(FeedbackMessage message)
{
if (message.getMessage() instanceOf DoNotDeleteMe) {
return false;
}
return message.isRendered();
}
Make sure you implement DoNotDeleteMe#toString() so that it renders properly. Or you will have to use a custom FeedbackPanel too.
DoNotDeleteMe must implement java.io.Serializable!

Eclipse PDE: Programmatically detect opened dialog and close it

On Eclipse Luna, I select a server and click the Start button on Servers view, then the server (for example Tomcat8) will get started. If something is wrong during the start-up process, a dialog will be populated to display the error messages (for example time-out). The dialog is modeless in this test case.
Now I need to start the server programmatically from a plugin. In case that errors occur, how could I programmatically detect that a dialog has been opened and how to close it?
You could use the Display.addFilter method to listen for all SWT.Activate events which will tell you about all Shells (and other things) being activated. You can then detect the shells you want to close.
Something like:
Display.getDefault().addFilter(SWT.Activate, new Listener()
{
#Override
public void handleEvent(final Event event)
{
// Is this a Shell being activated?
if (event.widget instanceof Shell)
{
final Shell shell = (Shell)event.widget;
// Look at the shell title to see if it is the one we want
if ("About".equals(shell.getText()))
{
// Close the shell after it has finished initializing
Display.getDefault().asyncExec(new Runnable()
{
#Override
public void run()
{
shell.close();
}
});
}
}
}
});
which closes a dialog called 'About'.
In more recent versions of Java the above can be simplified to:
Display.getDefault().addFilter(SWT.Activate, event ->
{
// Is this a Shell being activated?
if (event.widget instanceof Shell shell)
{
// Look at the shell title to see if it is the one we want
if ("About".equals(shell.getText()))
{
// Close the shell after it has finished initializing
Display.getDefault().asyncExec(shell::close);
}
}
});
This uses Java 8 lambdas and method references and Java 16 instanceof type patterns.

SWT - Tweaking my ProgressMonitorDialog

I have a working ProgressMonitorDialog, but I want to make sure that I am setting it up correctly.
First the Code:
Method to create Dialog
public void startProgressBar() {
try {
new ProgressMonitorDialog(getShell()).run(true, true,
new ProgressBarThread());
}
catch (InvocationTargetException e) {
MessageDialog.openError(getShell(), "Error", e.getMessage());
}
catch (InterruptedException e) {
MessageDialog.openInformation(getShell(), "Cancelled", e.getMessage());
}
}
Class File
class ProgressBarThread implements IRunnableWithProgress {
private static final int TOTAL_TIME = 1000;
public ProgressBarThread() {
}
public void run(IProgressMonitor monitor) throws InvocationTargetException,InterruptedException {
monitor.beginTask("Creating PDF File(s): Please wait.....", IProgressMonitor.UNKNOWN);
for (int total = 0; total < TOTAL_TIME ; total++) {
Thread.sleep(total);
monitor.worked(total);
if (total == TOTAL_TIME / 2) monitor.subTask("Please be patient... Operation should finish soon.");
}
monitor.done();
}
}
Method that calls the ProgressBar and runs a Pdf file creation Operation
private void startSavePdfOperation() {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
startProgressBar();
}
});
saveOp = new AplotSaveOperation(appReg.getString("aplot.message.SAVETOPDF"), "PDF", session);
saveOp.addOperationListener(new MyOperationListener(this) {
public void endOperationImpl() {
java.io.File zipFile = null;
try {
AplotSaveResultsParser.SaveResult saveResults = saveOp.getSaveResults();
if (saveResults != null) {
ETC..... ETC......
Questions:
Being the ProgressMonitorDialog is a GUI, it needs to be executed in a
Display.getDefault().asyncExec?
If the ProgressMonitorDialog is running in a separate thread, how does it know to close when the operation is finsihed?
Is there any relationship between the progressbar and the operation?
I am correct in assuming that the for loop in the ProgressBarThread class is basically the timer that keeps the monitor open?
Is there a way to increase the speed of the ProgressMonitorDialog's indicator, also can you remove the cancel button?
This is what I am thinking is happening currently.
I am starting the progress bar just before I start the PDF Operation Listener
See startSavePdfOperation() Above
The progress bar is running as unknown, but using a for loop to keep the progress bar dialog open, while the operation is running on a thread in the background.
See Class ProgressBarThread above
When the PDF operation completes the listener operation class closes the base GUI dialog.
public void endOperation() {
try {
endOperationImpl();
}
finally {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
w.getShell().setCursor(new Cursor(Display.getCurrent(), SWT.CURSOR_ARROW));
w.recursiveSetEnabled(getShell(), true);
w.getShell().setEnabled(!getShell().getEnabled());
w.close();
}
});
}
}
I am not sure what is happening to the ProgressBarThread monitor?
Is this Possible?
When the PDF Operation starts, the ProgressMonitorDialog opens and starts the indicator. OK with keeping it unknown.
When the PDF Operation completes, the monitor closes, then the base Dialog
I am just wanting to open progress bar dialog that will inform the user that their request is working in the background.
As stated the above code works, but I am afraid by letting the closing of Base GUI, destroy my Progress Thread and Monitor is not good practice.
First of all, in your ProgressBarThread#run() you should use monitor.worked(1). You don't need to set the total worked but increment it by the amount of work done, since the last time it was called.
Q1. Yes it needs to be executed in the display thread
Q2. Normally the work that needs to be done is actually performed in the runnable that is passed to the progress monitor dialog so that you can accurately report the amount of progress made. So your operation (if it is a synchronous call) should be called from within ProgressBarThread#run() so that you call monitor.worked(1) only when one file processing is complete.
Q3. What kind of operation are you running, perhaps it already supports showing progress bar, and you just need to invoke the right API. Is it an IUndoableOperation?
Q4. As I said this approach is problematic because you can never accurately report the progress and close the dialog only when the operation is completed. But if this is the only choice you have, then you can just save the monitor reference somewhere so that it is accessible to the other thread. Once monitor.done() is called, your ProgressBarThread#run() should return, the dialog will close.
Q5. You can remove the cancel button by passing the correct parameter to ProgressMonitorDialog#run(..):
new ProgressMonitorDialog(getShell()).run(true, false, new ProgressBarThread());
For the rest of the questions I can better answer if I know what kind of operation (what API) you are using.

second call of google maps does not show the map in correct size

using gwt-maps-3.8.0 i display a route in a gwt popup. Works when called once but does not work on second call.
What should i do ... some advice to refresh the mapWidget?
When you display the map, trigger its resize event.
From the documentation:
Developers should trigger this event on the map when the div changes size: google.maps.event.trigger(map, 'resize')
It appears the way to do this in GWT is
Event.trigger(mapWidget.getMap(), "resize");
At the moment, the map has zero size as far as the API is concerned, so it's just displaying the buffer of tiles around the single pixel at (0,0). Triggering the resize event causes the API to get the correct size from the browser so the right tiles are fetched for display.
I had the same issue (map shown in a popup; reload the popup and the map was no longer centered).
In the end I managed to fix my problem using the triggerResize method from the GoogleMap class. However it worked only after I triggered this method from an Idle event.
triggerResize will notify the map to show the correct tiles.
setCenter will make sure the map is centered once again.
gMap.addIdleListenerOnce(new IdleHandler() {
#Override
public void handle() {
gMap.triggerResize();
gMap.setCenter(myLatLng);
}
});
Using the GWT-V3-Maps-API it would be done as follows for a case where a div or window resizes:
/*
* Example of how to dynamically resize the map to fit the window - add
* your events
*/
Window.addResizeHandler(new ResizeHandler() {
#Override
public void onResize(ResizeEvent event) {
MapHandlerRegistration.trigger(mapWidget, MapEventType.RESIZE);
GWT.log("Window has been resized!");
}
});
mapWidget.addResizeHandler(new ResizeMapHandler() {
#Override
public void onEvent(ResizeMapEvent event) {
GWT.log("Map has been resized!");
}
});

Block gwt DisclosurePanel on open state

How may I block a gwt DisclosurePanel on the open state ?
I mean, how can I prevent this DisclosurePanel to close if the user click the header more than once ?
(My header is a textBox, I want the user to enter a text, and the panel should remain open if the user unfocus the textBox and focus newly by clicking it. The DisclosurePanel content has a "cancel" button that closes the panel)
Thank you very much.
I edit my question after 2 first answers: I would like to avoid to reopen the DisclosurePanel once closed to avoid flashing effect. I actually want to prevent the DisclosurePanel to close. Maybe sinkEvents can help me... if so, how? Thanks.
A NativePreviewHandler receives all events before they are fired to their handlers. By registering a nativePreviewHandler the first time your disclosurePanel is opened, you can cancel the click event. You can later decide to remove this handler by preventClose.removeHandler();
HandlerRegistration preventClose = null;
....
panel.addOpenHandler(new OpenHandler<DisclosurePanel>() {
#Override
public void onOpen(OpenEvent<DisclosurePanel> event) {
if (preventClose == null){
preventClose = Event.addNativePreviewHandler(new NativePreviewHandler() {
#Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
if (event.getTypeInt()==Event.ONCLICK && event.getNativeEvent().getEventTarget() == panel.getHeader().getElement().cast())
event.cancel();
}
});
}
}
});
The obvious answer is review the javadoc here: https://google-web-toolkit.googlecode.com/svn/javadoc/1.5/com/google/gwt/user/client/ui/DisclosurePanel.html
There is a setOpen() method that: Changes the visible state of this DisclosurePanel.
Set it to false from a click event to capture the user action.
The JavaDoc is right here: https://google-web-toolkit.googlecode.com/svn/javadoc/latest/com/google/gwt/user/client/ui/DisclosurePanel.html
jamesDrinkard pointed the old 1.5 javadoc.
You can use the addCloseHandler(CloseHandler<DisclosurePanel> handler) method to add a handler so when the user tries to close it you can reopen it again with setOpen().
Maybe not the best way, but it worked for me (maybe just one of both will work too):
dPanel.setOpen(true);
dPanel.addOpenHandler(new OpenHandler<DisclosurePanel>() {
#Override
public void onOpen(OpenEvent<DisclosurePanel> event) {
dPanel.setOpen(true);
}
});
dPanel.addCloseHandler(new CloseHandler<DisclosurePanel>() {
#Override
public void onClose(CloseEvent<DisclosurePanel> event) {
dPanel.setOpen(true);
}
});