简体   繁体   中英

Java JFrame Opens too small

I am trying to create PingPong in java, however I am having troubles creating boundaries for the ball. After testing, I found that the JFrame opens too small; I set the width to 500 and the JFrame opens at 484 pixels. 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:

public class Display extends 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. 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 .

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. That will give you 500x400 pixels to work with in your actual drawing.

Notice that I removed all the frame references. Since Display itself is already a JFrame you don't need to create another one. Just use the Display object itself.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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