Multiscreen Dialogs and the JFileChooser
I develop software on two monitors, one monitor dedicated for the IDE/debugger and one for running the application. But when you develop on two monitors you will soon notice that your dialogs will not always pop up on top on your application. I’ve already written a bit about dual monitor environments when talking about the GraphicsEnvironment class.
In this post, I’ll go over some code borrowed from a YourKit forum post on how to support multiscreen pop up dialogs in Java. A typical pops up dialog, like a file chooser, should be located on the center of the main application window, no matter on which monitor the main window is sitting on. To open and center a dialog on the currently selected frame you can use code like the following.
[source:java]
public static Point calculateCenter(Container popupFrame) {
KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
Window windowFrame = kfm.getFocusedWindow();
Point frameTopLeft = windowFrame.getLocation();
Dimension frameSize = windowFrame.getSize();
Dimension popSize = popupFrame.getSize();
int x = (int)(frameTopLeft.getX() + (frameSize.width/2) – (popSize.width/2));
int y = (int)(frameTopLeft.getY() + (frameSize.height/2) – (popSize.height/2));
Point center = new Point(x, y);
return center;
}
[/source]
If you are working with two monitors, you will also need to explicitly set the location on a JFileChooser object. If you don’t set the location on the file chooser and your main application in on the secondary monitory, the chooser will pop up on the primary. The problem with JFileChooser is that it does not respect the values you specify when you call the setLocation method.
Someone entered a bug on the JFileChooser because the x,y values on the setLocation method are ignored. The fix of this issue you need to subclass the JFileChooser.
[source:java]
JFileChooser chooser = new JFileChooser() {
protected JDialog createDialog(Component parent) throws HeadlessException {
JDialog dialog = super.createDialog(parent);
// …
Point p = calculateCenter(dialog);
dialog.setLocation(p.x, p.y);
return dialog;
}
};
int returnVal = chooser.showOpenDialog(this);
[/source]
Technorati Tags: java, jfilechooser, multiscreen, monitors, dialog