本文介绍了JFrame.getLocationOnScreen()用于最小化窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我致电 JFrame中的c0> .如果JFrame最小化-32000,则返回-32000.

I call getLocationOnScreen() from JFrame in my Swing application. If JFrame is minimized -32000, -32000 is returned.

预计:

计算机上的位置坐标显示X = -32000,Y = -32000

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

But I need to know the location of the window before it was minimized or would be the location if it is maximized again without actual maximizing it. Because I need to position JDialog relatively to the JFrame even though it is minimized.

可能的解决方案:WindowListener添加到JFrame,并在windowIconified()事件上保存坐标.然后使用它代替getLocationOnScreen().

Possible solution:Add WindowListener to JFrame and on windowIconified() event save the coordinates. And then use it instead of getLocationOnScreen().

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

Is there better solution using only JFrame methods?

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

Multiscreen 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

推荐答案

只需使用getLocation().是否最小化,它将始终返回适当的值:

Simply use getLocation(). Minimized or not, it will always return 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();
            }

        });
    }
}

这篇关于JFrame.getLocationOnScreen()用于最小化窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 22:10