I am writing a chess program. For displaying the chessboard I am using two JPanel
s:
- chessboard: This panel displays an image of an empty chessboard
- chessmen: This panel displays an array of
JLabel
s with chessmen images
So for this I need the two panels on top of each other. Therefore I am presently using a JLayeredPane
. But the problem is I can only view only one of the layers at once.
My present code for the constructor is:
public ChessBoard(){
setLayout(new FlowLayout());
gamescreen = new JLayeredPane();
gamescreen.setPreferredSize(new Dimension(200,200));
chessboard = new JPanel(new GridBagLayout());
chessmen = new JPanel(new GridBagLayout());
//chessboard.setLocation(0, 0);
//chessmen.setLocation(0,0);
chessboardImage = new ImageIcon(getClass().getResource("chessboard.jpg"));
chessboardDisplay = new JLabel(chessboardImage);
chessboard.add(chessboardDisplay);
GridBagConstraints constraint = new GridBagConstraints();
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
imageSet[i][j] = new ImageIcon(getClass().getResource(""+i+(j+1)+".png"));
image = imageSet[i][j].getImage().getScaledInstance(100, 100, Image.SCALE_SMOOTH);
imageSet[i][j]= new ImageIcon(image);
}
}
for(int i=0;i<2;i++){
constraint.gridy=i+3000;
for(int j=0;j<2;j++){
chessmenPos[i][j] = new JLabel(imageSet[i][j]);
constraint.gridx=j;
chessmen.add(chessmenPos[i][j],constraint);
}
chessboard.setBounds(0, 0, 200, 200);
chessmen.setBounds(0, 0, 200, 200);
gamescreen.add(chessboard, 1);
gamescreen.add(chessmen, 0);
gamescreen.setOpaque(false);
chessboard.setVisible(true);
chessmen.setVisible(true);
add(gamescreen);
}
EventHandling eventHandler = new EventHandling();
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
chessmenPos[i][j].addMouseListener(eventHandler);
}
Where am I going wrong and what changes can I make?