Java 如何准确获得JFrame';什么内容?

Java 如何准确获得JFrame';什么内容?,java,swing,jframe,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); fr

这是我的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;
}
public-double-getX(){
如果(xGame.width-6)
x=Game.width-6-getImage().getWidth(null);
返回x;
}
公共双盖{
如果(Y名称高度-26)
y=Game.height-26-getImage().getHeight(null);
返回y;
}
有办法解决这个问题吗?我不认为JFrame在每个人的计算机上都是相同大小的,更不用说猜测了。相反,通过使用JFrame组件中的现有变量,使其更加整洁和灵活。是否存在类似frame.getDisplayWidth和Height的函数?

  • 不要设置框架的大小,请设置内容的首选大小
  • 装好架子
  • 根据内容中的位置获取坐标

如何为内容设置“首选大小”?我正在使用
屏幕
类(扩展的
JPanel
)进行渲染


看起来你想做一个全屏应用程序。JFrame的setdecorned(false)将删除标题和边框。setBounds进行大小调整。

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


此外,为了防止您需要找出框架装饰(标题栏和边框)的实际大小,不需要猜测——您可以通过调用
JFrame.getInsets()

来获取此信息。如何设置内容的“首选大小”?我正在使用Screen类进行渲染,其中有一个方法(Graphics x),但是我不知道如何设置它的大小。Screen类扩展了什么?
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());