Reputation: 373
I'm working on a simple 2D game in Java. My problem is that my window appears to be larger than what I set it to be. I set it to be 800 x 800, however, as you can see from my picture, the sample rectangle which at the bottom is only at 750. If I put it at 800, it will be off the screen.
Main
JFrame myFrame = new JFrame();
myFrame.setSize(800,800);
world map = new world();
myFrame.add(map);
Map
//The only way I can get this to the bottom is setting it to 750. But my window is 800, where
//did the extra 50 pixels go?
g2d.draw3DRect(400, 750, 29, 20, true);
Upvotes: 0
Views: 371
Reputation: 324108
The frame may be 800 x 800, but the panel where you do the custom painting is less than that because the frame decorations (titlebar and border) take up space.
Check out this little piece of code to demonstrate this:
import java.awt.*;
import javax.swing.*;
public class FrameInfo
{
public static void main(String[] args)
{
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
Rectangle bounds = env.getMaximumWindowBounds();
System.out.println("Screen Bounds: " + bounds );
GraphicsDevice screen = env.getDefaultScreenDevice();
GraphicsConfiguration config = screen.getDefaultConfiguration();
System.out.println("Screen Size : " + config.getBounds());
System.out.println(Toolkit.getDefaultToolkit().getScreenSize());
JFrame frame = new JFrame("Frame Info");
// JDialog frame = new JDialog();
System.out.println("Frame Insets : " + frame.getInsets() );
frame.setSize(200, 200);
// frame.pack();
System.out.println("Frame Insets : " + frame.getInsets() );
frame.setVisible( true );
System.out.println("Frame Size : " + frame.getSize() );
System.out.println("Frame Insets : " + frame.getInsets() );
System.out.println("Content Size : " + frame.getContentPane().getSize() );
}
}
The key is that you should NOT be using the setSize() method on the frame.
Instead, in your custom panel you override the getPreferredSize()
method to return 800 x 800 and then you invoke:
frame.pack();
frame.setVisible(true);
Now all the components will be displayed at their preferred sizes.
Also, class names should start with an upper case character. "map" should be "Map". Take a look at the Java API and you will notice this. Don't make up your own conventions!
Upvotes: 3
Reputation: 1746
When you use JFrame.setSize(int width, int height)
you actually set the size of the whole window. this of course includes the decorations and title bar, which take up some of the space. In your case this seems to be about 50 pixels. Try setting the inner bounds of the JFrame by using getContentPane().setPreferredSize(new Dimension(800,800));
instead.
Edit: you need to call pack()
on the JFrame somewhere for it to actually resize the Window.
Upvotes: 3