简体   繁体   English

Java JFrame 打开太小

[英]Java JFrame Opens too small

I am trying to create PingPong in java, however I am having troubles creating boundaries for the ball.我正在尝试在 Java 中创建 PingPong,但是我在为球创建边界时遇到了麻烦。 After testing, I found that the JFrame opens too small;经过测试,发现JFrame打开太小; I set the width to 500 and the JFrame opens at 484 pixels.我将宽度设置为 500,JFrame 以 484 像素打开。 Why is this?为什么是这样?

Here is my game class:这是我的游戏课:

public class Game extends Canvas {公共类游戏扩展画布{

public static void main(String[] args){
    new Game();
}

Display d;


public Game(){
    d = new Display(this);
    requestFocus();
}


public void start(){
    System.out.println("Game started.");
}
public void stop(){

}


public void paint(Graphics g){
    g.setColor(Color.DARK_GRAY);
    g.fillRect(0, 0, 500, 400);
    g.setColor(Color.GREEN);
    g.drawLine(483, 0, 483, 399);
    g.drawLine(0, 399, 499, 399);
}

} }

Here is my JFrame class:这是我的 JFrame 类:

public class Display extends JFrame {公共类显示扩展 JFrame {

JFrame frame;
Dimension screenSize;

public Display(Game game){
    frame = new JFrame("PingPong");
    screenSize = new Dimension(500, 400);



    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(true);
    //frame.setSize(500, 400);
    frame.setPreferredSize(screenSize);
    frame.setMinimumSize(screenSize);
    frame.setMaximumSize(screenSize);

    frame.setLocationRelativeTo(null);
    frame.add(game);
    //frame.pack();
    game.start();

}

} }

When you call setSize on a JFrame , it includes the size of the title bar, as well as any other decoration around the window.当您在JFrame上调用setSize时,它包括标题栏的大小,以及窗口周围的任何其他装饰。 So the actual drawable area you have is going to be a bit less than that.因此,您拥有的实际可绘制区域将比这少一点。 You can work around this by setting your Game 's preferred size, and using pack on the JFrame .您可以通过设置Game的首选大小并在JFrame上使用pack解决此问题。

So if you change your code to this:因此,如果您将代码更改为:

public Display(Game game){
    super("PingPong");
    screenSize = new Dimension(500, 400);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setResizable(true);
    game.setPreferredSize(screenSize);

    setLocationRelativeTo(null);
    add(game);
    pack();
    setVisible(true);
    game.start();
}

It will work.它会起作用。 This tells your actual game what size it wants to be (500x400), and then has the frame resize so that it can fully contain it.这会告诉你的实际游戏它想要的大小(500x400),然后调整框架大小,以便它可以完全包含它。 That will give you 500x400 pixels to work with in your actual drawing.这将为您提供 500x400 像素以用于您的实际绘图。

Notice that I removed all the frame references.请注意,我删除了所有frame引用。 Since Display itself is already a JFrame you don't need to create another one.因为Display本身已经是一个JFrame你不需要再创建一个。 Just use the Display object itself.只需使用Display对象本身。

只需删除frame.pack()然后它就会工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM