最小化窗口的JFrame.getLocationOnScreen()

时间:2013-01-21 12:23:37

标签: java swing jframe jdialog

我在Swing应用程序中从JFrame致电getLocationOnScreen()。如果JFrame最小化-32000,则返回-32000。

预计:

Location Coordinates On Computer Showing X=-32000, Y=-32000

但是我需要知道窗口在最小化之前的位置,或者如果它在没有实际最大化的情况下再次最大化,那么它将是位置。因为我需要将JDialog相对于JFrame定位,即使它已被最小化。

可能的解决方案:WindowListener添加到JFrame并在windowIconified()事件中保存坐标。然后使用它而不是getLocationOnScreen()

仅使用JFrame方法是否有更好的解决方案?

需要多屏幕配置,并使用以下代码。

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

1 个答案:

答案 0 :(得分:4)

只需使用getLocation()即可。最小化与否,它将始终返回适当的值:

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

        });
    }
}