繁体   English   中英

最小化窗口的JFrame.getLocationOnScreen()

[英]JFrame.getLocationOnScreen() for minimized window

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

预计:

计算机上的位置坐标显示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

只需使用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();
            }

        });
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM