I am trying to make a simple game in Java. I set a size of my frame in this way:
getContentPane().setPreferredSize(new Dimension(1280, 720));
And then I added a JComponent object, which draws whole graphics in my game:
getContentPane().add(gameGraphics);
And it all seemed to work properly, till I tried to prevent game objects from going out-of-map. "Game engine" teleports every object that went below 0 or above 720 in height or 1280 in width. I am sure that algorithm works perfectly (I checked it very precisely) and just look what happens when I try to reach lower-right corner of the window (while upper-left works properly!):
(A player is that blue rectangle in a corner)
There is a 10-pixel line of free space on the right and down of the window. So a content of the window must be bigger than 1280x720 pixels. Do you have any ideas what is wrong here? Thanks.
There is a whole JFrame code:
MainFrame() {
super("GameOne");
setLayout(new BorderLayout());
getContentPane().setPreferredSize(new Dimension(RES_WIDTH, RES_HEIGHT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameGraphics = new GameGraphics();
getContentPane().add(gameGraphics);
new Player();
new TestShip(10, 10);
pack();
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}
GameGraphics as I said is a class that extends JComponent and everything which can be seen in the game is generated in a paintComponent method of this class.
RES_WIDTH and RES_HEIGHT are constants that are equal to 1280 and 720 respectively.
PROBLEM SOLVED:
A solution is to override a JComponent class's getPreferredSize() method (in my application it will be in GameGraphics class) (many layout managers ask every component for that and pack() method also does it). You just need to make it return a size (in 'Dimension') you want it to have. Also it's probably better to make a JFrame 'setResizable(false)' before you call pack().