-2

I am writing a Game in Java, and I don't want to use a layout manager for my JFrame. My class extends JFrame, and looks something like this:

//class field
static JPanel contentPane;

//in the class constructor
this.contentPane = new JPanel();
this.contentPane.setLayout(null);
this.setContentPane(contentPane);

I want my JPanel be exactly 600x600 px, but when I set the size of my JFrame by calling the this.setSize(600,600) method, the JPanel size is less than the 600x600 px because the border of the JFrame window is included too.

How can I set the size of the JPanel to be exactly 600x600 px?

P.S. I have seen all of the previous post and none of them work for me. For example: Get the real size of a JFrame content does not work for me. What else can I do?

Community
  • 1
  • 1
kolah ghermezi
  • 91
  • 2
  • 10
  • Can you be more specific than *"does not work for me"*? – jonrsharpe Aug 31 '15 at 10:22
  • for instance when I call 'this.pack();' the frame **only displays** the minimum, maximum (title bar) – kolah ghermezi Aug 31 '15 at 10:40
  • 1
    *"I am writing a Game in Java and because of that, I don't want to use a layout manager for my JFrame."* Use custom rendering and layouts become irrelevant. – Andrew Thompson Aug 31 '15 at 10:44
  • Have you tried setting the min/max size of the JPanel to the size you want? – Craig Aug 31 '15 at 10:57
  • when I write 'System.out.println(this.getContentPane().getSize());' I get 'java.awt.Dimension[width=0,height=0]' – kolah ghermezi Aug 31 '15 at 10:58
  • I think what you need is to set the preferred size, and possibly the minimum maximum sizes. Take a look at http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#setPreferredSize(java.awt.Dimension) and use it on your JPanel contentPane. – Craig Aug 31 '15 at 11:43

2 Answers2

1

If you don't need the Frame-Decorations (icon, title, min/max/close-buttons and the border), you can make a Frame undecorated, then it has exactly the size you gave it

java.awt.Frame.setUndecorated(boolean)
hinneLinks
  • 3,673
  • 26
  • 40
1

How can I set the size of the JPanel to be exactly 600x600 px?

Override the getPreferredSize() method of your custom game panel to return the size you want the panel to be.

@Override Dimension getPreferredSize()
{
    return new Dimension(600, 600);
}

Then the basic code to create your frame will be:

GamePanel panel = new GamePanel();
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);

Now all your game logic will be contained in the GamePanel class.

camickr
  • 321,443
  • 19
  • 166
  • 288