JLabel Dragging with Container as opposed to JLayeredPane
As I am working on my chess GUI, i have reached the part of moving the pieces through the mouse clicking on a piece to select it, dragging it, and then releasing the mouse to drop it into the JPanel under it that functions as the board square. I have looked through some things online and have seen that most other people use JLayeredPane as opposed to Container. My program uses Container and I was wondering as how to produce the same results as using Container as with using JLayeredPane.DRAG_LAYER ?
Re: JLabel Dragging with Container as opposed to JLayeredPane
The basic idea of dragging things around is:
* detect mouse down and decide is something is being dragged. An instance variable should remember what is being dragged and where (the coordinates) the drag started.
* detect mouse drag and decide, based on position, how to update your display. In your case you could update the position of the piece.
* detect mouse up. If there is a drag in progress end it: reset the variable remembering what was being dragged, decide - based on the rules of chess - whether it was a valid move and, if so, "snap" the position of the piece into place. If it is invalid the position should probably be reset to its original position.
-----
Are you sure you don't want to use the drag layer? JLayeredPane *is* a container, after all. And it's one that has a notion of "z-position" (above/below). A problem with merely changing the position of a piece is that it may well disappear behind another as it is being dragged. JLayeredPane lets you solve this by:
* putting the piece into the drag layer
* dragging it as above
* returning it to the container once the drag is done
-----
Quote:
I have looked through some things online
Other people's code is only so much good. (as you've found) As far as things online go I would recommend the How to Use Layered Panes page of Oracle's Tutorial to get a feel for how these things are used. They seem a good "fit" for what you're trying to do.
-----
Just an aside, but you might want to consider not shoving everything into one class. I'm thinking that the game state (which piece is in which position) might deserve a class of its own (in place of your array of panels). This class could be responsible for chess-related behaviour like deciding whether some position is a valid move for a given piece, independently of GUI stuff like painting and responding to mouse drags. As the program becomes more involved having classes with definite (and independent) responsibilities is a good way of managing the complexity.
Re: JLabel Dragging with Container as opposed to JLayeredPane
Alright, thanks for all the great info and advice :)
Re: JLabel Dragging with Container as opposed to JLayeredPane