1

I'm building a simple 2D game in Java.

I'm using the JFrame class, but I don't think the width and height are what I specified, or perhaps the graphics are incorrect.

Here are some snippets of my code:

public final static int WIDTH = 600, HEIGHT = 900;
JFrame frame = new JFrame();
frame.setSize(WIDTH, HEIGHT);
g.setColor(Color.BLACK);
g.fillRect(0, 0, WIDTH, HEIGHT - 10);

The JFrame is displaying a black background. However, based on the arguments I gave to the fillRect function, there should still be a 10px tall sliver of white at the bottom of the frame. This is not the case. The white sliver only really starts to show after a 30px decrease from the height of the frame.

Thanks for your help.

Ansharja
  • 1,237
  • 1
  • 14
  • 37
Jack
  • 57
  • 7
  • Possible duplicate [How to get the EXACT middle of a screen, even when re-sized](https://stackoverflow.com/questions/13457237/how-to-get-the-exact-middle-of-a-screen-even-when-re-sized/13460914#13460914); [How can I set in the midst?](https://stackoverflow.com/questions/13734069/how-can-i-set-in-the-midst/13734319#13734319); [Graphics rendering in title bar](https://stackoverflow.com/questions/13313084/graphics-rendering-in-title-bar/13316131#13316131) – MadProgrammer Aug 01 '20 at 22:55

1 Answers1

5

The JFrame size includes the borders so you need to allow for them. To facilitate dealing with this don't specify the width and height of the JFrame. I recommend doing the following.

JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(width,height));
frame.add(panel);
// add other components in the panel
frame.pack();
// center on screen.
frame.setLocationRelativeTo(null);
frame.setVisible(true);

Now your panel will be the specified size.

Note, if your going to paint, make certain you override paintComponent(Graphics g) in JPanel and do your painting there.

@Override
public void paintComponent(Graphics g) {
   super.paintComponent(g);
   // your code here
}
WJS
  • 36,363
  • 4
  • 24
  • 39