JFrame.getLocationOnScreen () for minimized window

I am calling getLocationOnScreen()

from JFrame

in my Swing application. If JFrame

-32000 is minimized, -32000 is returned.

Expected:

Location coordinates on computer Display X = -32000, Y = -32000

But I need to know the location of the window before it was minimized, or what would be the location if it would be maximized again without actually maximizing it. As I need to position JDialog

relatively JFrame

even if it is minimized.

Possible solution: Add coordinates WindowListener

to JFrame

and windowIconified()

store coordinates in the event. And then use it instead getLocationOnScreen()

.

Is there a better solution using only methods JFrame

?

A multi-screen configuration is expected and the following code is used.

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] gs = ge.getScreenDevices();
    for (int j = 0; j < gs.length; j++) {
        GraphicsDevice gd = gs[j];
        GraphicsConfiguration[] gc = gd.getConfigurations();
        for (int i = 0; i < gc.length; i++) {
            Rectangle gcBounds = gc[i].getBounds();
            Point loc = topContainer.getLocationOnScreen(); //might return -32000 when minimized
            if (gcBounds.contains(loc)) { //fails if -32000 is returned

      

+3


source to share


1 answer


Just use getLocation()

. Minimized or not, it always returns the appropriate value:



import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestJFrame {

    public void initUI() {
        final JFrame frame = new JFrame(TestJFrame.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        frame.setVisible(true);
        Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                System.err.println(frame.getLocation());
            }
        }, 0, 1000, TimeUnit.MILLISECONDS);
    }

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
            UnsupportedLookAndFeelException {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestJFrame().initUI();
            }

        });
    }
}

      

+4


source







All Articles