【发布时间】:2014-04-15 03:47:51
【问题描述】:
我正在创建一个多用户 Swing GUI 应用程序,并希望用户的窗口位置和大小设置在他们注销和重新登录时保持不变。我目前正在使用 getLocation() 和 @987654323 获取窗口位置和大小当用户注销并将它们保存到文件时,我的父 JFrame 上的 @ 方法,然后当用户重新登录时,我将这些值读回并使用 setLocation() 和 setSize() 设置窗口大小和位置。
我遇到的问题是getLocation() 和getSize() 似乎从系统边框中减去(例如,如果我将窗口放在左上角getLocation 返回(1,54) 而不是(0,0) ),但 setLocation() 和 setSize() 没有。结果是每次我注销并重新登录时,窗口都会出现轻微偏移,并且比我关闭它时稍微小。
有人知道为什么会发生这种情况或我该如何解决吗?我应该使用其他方法来获取和设置窗口位置和大小吗?
如果有帮助,我正在 Ubuntu 12.04 上运行 java 1.7.0_45。
谢谢!
编辑:
以下示例复制了我看到的问题:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public class JFrameTest
{
private JFrame frame;
private JButton button;
private Point lastLocation;
private Dimension lastSize;
private void run()
{
button = new JButton("Test");
button.addActionListener(listener);
lastLocation = new Point(0, 0);
lastSize = new Dimension(200, 200);
initFrame();
}
private void initFrame()
{
frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.getContentPane().add(button);
frame.setLocation(lastLocation);
frame.setPreferredSize(lastSize);
frame.pack();
frame.setVisible(true);
}
private ActionListener listener = new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == button)
{
lastLocation = frame.getLocationOnScreen();
lastSize = frame.getSize();
frame.dispose();
initFrame();
}
}
};
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run()
{
new JFrameTest().run();
}
});
}
}
另外,当我使用 getLocationOnScreen() 而不是 getLocation() 时,我看到了同样的问题。
【问题讨论】:
-
实际上runnable example that demonstrates your problem 将涉及更少的猜测工作和更好的响应
-
如果你使用
setLocationByPlattform(true)我认为在 ubuntu 中将屏幕放在右上角 0,0 -
@MadProgrammer - 我包含了一个可运行的示例来复制我的问题;谢谢你的建议。 @nachokk - 感谢您的反馈,但在上面的示例代码中调用
frame.setLocationByPlatform(true)似乎无法解决问题 -
我要为这个很棒的例子加1!好的。虽然对你完全没用,但它可以在 Windows 上运行......可能是某个地方的错误......
-
你应该
pack()之前你setLocation()。