Search code examples
javaswingjframecollision-detectiongame-physics

My JFrame size doesn't match up with set size


I am using frame.setSize(480, 400) to set the size of my JFrame. Despite this, when I am doing some collision checking (I am making a breakout game), the ball goes completely off the bottom of the screen, then finally bounces. This is the collision code I'm using: if (YPos + height >= MainClass.height) { YVel = YVel * -1; }. The static height variable is what is set to 400, and used in the frame.setSize call. This has happened in my pong game aswell, although I fixed it with some hard set values. I wouldn't like to repeat this though, as this is bad practice.

Thanks for any responses, Rees.


Solution

    1. don't to set frame.setSize(480, 400) or frame.setPreferredSize(480, 400)

    2. for painting to use JPanel / JComponent, then return coordinates from this container

    3. painting in Swing by default never returns any PreferredSize have to override PreferredSize for JPanel / JComponent, (see dim.width, dim.height this methods returns proper coordinates for Object(s) added to JPanel / JComponent, after resize too)

    4. then call (last code lines) JFrame.pack() and JFrame.setVisible(true)

    5.JFrame doesn't returns proper coordinated have to calculating with its Borders and Toolbar, but ContentPane return inner and proper size