Continuing my quest of learning Java by doing a simple game, i stumbled upon a little issue. My gameboard extends JPanel as well as each piece of the board. Now, this presents some problems:
-
Cant set size of each piece, therefore, each piece JPanel ocupy the whole JFrame, concealing the rest of the pieces and the background (gameboard).
-
Cant set the position of the pieces.
I have the default flow manager. Tried setbounds and no luck.
Perhaps i should make the piece to extend other JComponent?
Added image:
That’s the piece, now the greyed area is also the piece! Checked that by making a mousePressed listener and assigning some stuff to it. Below the grey area, is the gameboard (or at least, should be!), another JPanel.
alt text http://img42.imageshack.us/img42/2227/screenshotvdy.png
Some code:
package TheProject;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GameWindow extends JFrame {
public GameWindow() {
setSize(800, 600);
setLocationRelativeTo(null);
Map map = new Map(800, 600, 2);
add(map);
MilitaryUnit imperialRussia = new MilitaryUnit(30, Color.BLACK, Color.YELLOW, Color.WHITE);
imperialRussia.setPreferredSize(new Dimension(30, 30));
add(imperialRussia);
}
}
This happens when i apply the pack() method:
alt text http://img442.imageshack.us/img442/5813/screenshot2ml.png
Packs around the Unit, not the map which is bigger and fills the JFrame.
I wrote a few games using
JPanel. Basically the way I useJPanelis like I’m using aCanvas, viz I draw directly on it by overriding thepaint()method. The reason why I useJPanelis because I can determine the size of my game world, then use thesetPreferredSize()to set the size of the panel. I then add the panel to aJScrollPane. So this will take care of the panning, etc.Say I’m writing a 2D game. This is how I use JPanel. I have a logical map (a 2D array) which holds my game map. Say each location is 32×32 pixel. So you start drawing the ground and what is on that ground in that location. eg in x=1, y=2 which is screen location x=32, y=64, you draw the ground first, then draw what is on the ground. So a rough outline of the render loop would be something like this
You set a
MouseListenerlistener to the JPanel, so every mouse click you translate back to the map eg. mouse click x=54, y=72 would correspond to x=1, y=2. The calculation is a bit tricky if you have an isometric view.The thing you have to be careful here is that everytime when you scroll the panel via the scroll panel,
paint()will be called. So it is good to render your game board on aBufferedImageand then in thepaint()method just draw theBufferedImageotherwise it’ll be too slow.