in making a chess game in java using JPanel,is there a method that returns whether the container contains anything? for example by defining an array like this: JPanel [8][8] we want to check if there is a man in the square[i][j], so that we can check whether the players move is legal or not. is there a method to check that??
-
1for better help sooner post an [SSCCE](http://sscce.org/), short, runnable, compilable, just about a.m. described issue – mKorbel Dec 29 '12 at 09:51
-
There are numerous ways to get a component from within a `JPanel`, you can take a look at the `getComponent` methods. However, the most sane way would be to keep a separate, 2-dimensional array of field references independent from the implementation of `JPanel` itself. – toniedzwiedz Dec 29 '12 at 09:57
-
1See also this [example](http://stackoverflow.com/a/2562685/230513) and [variation](http://stackoverflow.com/a/2563350/230513). – trashgod Dec 29 '12 at 11:40
2 Answers
Instead of checking the JPanel, I would recommend storing the current board position in a separate data structure. You would typically define a class to store the board with accessor functions to access the pieces, e.g. something like:
public class Board {
private Piece[][] squares;
....
code to set up board etc.
....
public Piece getPiece(int x, int y) {
return squares[x][y];
}
}
This approach gives you several advantages:
- You decouple the representation of the board position from the GUI display. This is important - you typically want to do stuff with Board positions (e.g. evaluate them, search for possible moves etc.) without being tied to the screen display.
- You can structure the internal representation of the board any way you like, whilst presenting a nice encapsulated view to other code that uses the board
- Performance will be better: a simple in-memory representation of the board is a lot more lightweight and faster to access than querying / modifying a tree of GUI components.

- 105,238
- 25
- 256
- 415
send me a message, I'm having computer trouble and can't seem to post a comment at the moment but I made a checkers game a while back and I'll send you the source code. its not complete but it does draw the board and pieces. it also checks for mouse clicks and playable squares. it maybe useful as a reference. a quick answer to your question is I wouldn't use a JPanel
, instead create a Space class that extends Rectangle
or Rectangle2D
, those classes have methods to do what you want and as far as I know the JPanel
class does not.

- 256
- 1
- 2
- 9