I am trying to make some JLabels switch places with eachother on a JPanel with GridLayout on key pressed.
So far:
1. I can only make them react to a mouse click.
2. They can only switch places with the one above it and to its left.
Note:
1. If I set movePlayer(1) it works. And switches a JLabel from the grid (8,7) with an image of the player with one of the JLabels with an image of a floor above it. However my problem is, when i set movePlayer(2) it gives me and index out of bouds exception.
2. This is only part of the code which I believe to be relevant to the issue:
JPanel myCentrePanel = new JPanel();
MapElement[][] myMap = new MapElement[8][7];
public TileSwitching(){
super("TileSwitching");
setSize(400,400);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
myCentrePanel.setLayout(new GridLayout(8,7));
myCentrePanel.setPreferredSize(new Dimension(5,5));
add(myCentrePanel);
loadMap(level1);
drawMap();
myCentrePanel.setFocusable(true);
myCentrePanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
movePlayer(1);
myCentrePanel.removeAll();
drawMap();
myCentrePanel.revalidate();
}
});
myCentrePanel.setBackground(Color.CYAN);
}
public void movePlayer(int dir){
if(dir == 1){
for(int i = 0; i<8; i++){
for(int j= 0; j<7; j++){
if (myMap[i][j].getClass() == wk.getClass()){
myMap[i-1][j] = new Player();
myMap[i][j] = new Floor();
}
else{
myMap[i][j] = myMap[i][j];
}
}}
if(dir == 2){
for(int i = 0; i<8; i++){
for(int j= 0; j<7; j++){
if (myMap[i][j].getClass() == wk.getClass()){
myMap[i+1][j] = new Player();
myMap[i][j] = new Floor();
}
else{
myMap[i][j] = myMap[i][j];
}
}}
}
public static void main(String[] args) {
TileSwitching tl = new TileSwitching();
TileSwitching.setVisible(true);
}
What isn't shown in the code above:
1.MapElement
is a parent class(inherits) to many subclasses.
2.loadMap()
reads out chars (E.g. a,b,c...)from an array of chars to fill the array myMap with a new instance of a subclass of MapElement(E.g. new Player(),new Floor(),new Tree()
).
3.drawMap()
adds JLabels
to the JPanel
according to the class of of
myMap[i][j]
4.(Both methods were done with double For loops i<8, j<7(to fill the
GridLayout(8,7)
.
Thank you, sorry for the bad coding and noobishness, hope this is clear. Feel free to suggest a better way to move a player (JLabel)
on a JPanel
with a GridLayout
. And remember, the main question is: Why does (dir == 1)
work and (dir == 2)
doesn't?!