我调用getLocationOnScreen()
来 self 的 Swing 应用程序中的 JFrame
。如果 JFrame
最小化为 -32000,则返回 -32000。
预计:
Location Coordinates On Computer Showing X=-32000, Y=-32000
但是我需要知道窗口在最小化之前的位置,或者如果它在没有实际最大化的情况下再次最大化时的位置。因为我需要相对于 JFrame
定位 JDialog
,即使它已最小化。
可能的解决方案:
将 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();
}
});
}
}
关于java - 最小化窗口的 JFrame.getLocationOnScreen(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14438539/