如何准确获取JFrame内容的坐标?

时间:2011-11-20 09:10:36

标签: java swing jframe

这是我的JFrame代码:

public static int width = 800;
public static int height = 600;

public static void main(String[]args){
    JFrame frame= new JFrame("RETRO");
    frame.add(new Screen());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(width,height);
    frame.setVisible(true);
    frame.setResizable(false);
}

基本上当我想要移动到屏幕的边缘时,我必须添加额外的像素才能工作(我猜是因为它包含框架本身而不仅仅是显示尺寸?但是起源工作正常( x = 0,y = 0))。例如:

public double getX(){
    if(x<0)
        x=0;
    if(x+getImage().getWidth(null)>Game.width-6)
        x=Game.width-6-getImage().getWidth(null);
    return x;
}

public double getY(){
    if(y<0)
        y=0;
    if(y+getImage().getHeight(null)>Game.height-26)
        y=Game.height-26-getImage().getHeight(null);
    return y;
}

有解决方法吗?我不认为JFrame在每个人的计算机上都是相同的大小,更不用说猜测了。而是通过使用JFrame组件中的退出变量使其更加整洁和灵活。是否存在类似frame.getDisplayWidth和Height函数的内容?

3 个答案:

答案 0 :(得分:3)

  • 不要设置框架的大小,设置内容的首选大小。
  • 打包框架
  • 根据内容中的位置获取坐标

  

如何为内容设置“首选尺寸”?我正在使用Screen类(扩展JPanel)进行渲染。

screen.setPreferredSize(new Dimension (600,400));
frame.setContentPane(screen);
frame.pack();
// frame will now be the size it needs to display the contents 
// and the frame's own decorations (title bar etc.)
// ..now add a nice tweak.
frame.setMinimumSize(frame.getSize());

答案 1 :(得分:0)

似乎你想要做一个像全屏应用程序的东西。 JFrame的setDecorated(false)将取消标题和边框。 setBounds进行大小调整。

答案 2 :(得分:0)

尝试设置内容的首选大小(在您的情况下为Screen对象),而不是显式设置框架的大小。

另外,如果您需要找出框架装饰的实际尺寸(标题栏和边框),则无需猜测 - 您可以通过调用JFrame.getInsets()来获取此信息