0

I am writing a chess program. For displaying the chessboard I am using two JPanels:

  1. chessboard: This panel displays an image of an empty chessboard
  2. chessmen: This panel displays an array of JLabels 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?

CoderBrain
  • 103
  • 1
  • 11

1 Answers1

2

But the problem is I can only view only one of the layers at once.

The top layer needs to be transparent. So you would need:

chessmen.setOpaque( false );

You can check out: Asking for some clarification in java about jlabel and parent for an example of a simple chessboard. It uses a slightly different approach. Each square is a component.

camickr
  • 321,443
  • 19
  • 166
  • 288