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.

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;
}

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.

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);

Technorati Tags: , , , ,

Related posts:

  1. Class HighLite GraphicsEnvironment
  2. Extreme GUI Makeover 2007
  3. Outlook Fun With Scriptom
  4. Shutdown Remote Windows
  5. The Anatomy of a JavaScript Bookmarklet

This entry was posted in Java, TechKnow. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Posted March 6, 2008 at 8:25 pm | Permalink

    This helped me out a lot. Just wanted to say thanks!

  2. Martin
    Posted April 6, 2011 at 12:18 am | Permalink

    This was just what I was looking for. I can’t believe the multi monitor issue is not mentioned in the Javadoc.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*