surviveFocusChange=true
- by Geertjan
Here's a very cool thing that I keep forgetting about but that Jesse reminded me of in the recent blog entries on Undo/Redo: "surviveFocusChange=true".
Look at the screenshot below. You see two windows with a toolbar button. The toolbar button is enabled whenever an object named "Bla" is in the Lookup. The "Demo" window has a "Bla" object in its Lookup and hence the toolbar button is enabled when the focus is in the "Demo" window, as shown below:
Now the focus is in the "Output" window, which does not have a "Bla" object in its Lookup and hence the button is disabled:
However, there are scenarios where you might like the button to remain enabled even when the focus changes. (One such scenario is the Undo/Redo scenario in this blog a few days ago, i.e., even when the Properties window has the focus the Undo/Redo buttons should be enabled.)
Here you can see that the button is enabled even though the focus has switched to the "Output" window:
How to achieve this? Well, you need to register your Action to have "surviveFocusChange" set to "true". It is, by default, set to "false":
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle.Messages;
@ActionID(category = "File", id = "org.mymodule.BlaAction")
@ActionRegistration(surviveFocusChange=true, iconBase = "org/mymodule/Datasource.gif", displayName = "#CTL_BlaAction")
@ActionReferences({
@ActionReference(path = "Toolbars/Bla", position = 0)
})
@Messages("CTL_BlaAction=Bla")
public final class BlaAction implements ActionListener {
private final Bla context;
public BlaAction(Bla context) {
this.context = context;
}
@Override
public void actionPerformed(ActionEvent ev) {
// TODO use context
}
}
That's all. Now folders and files will be created in the NetBeans Platform filesystem from the annotations above when the module is compiled such that the NetBeans Platform will automatically keep the button enabled even when the user switches focus to a window that does not contain a "Bla" object in its Lookup. Hence, the same "Bla" object will remain available when switching from one window to another, until a new "Bla" object will be made available in the Lookup.