質問

I am making chess in Java and I have a board with black and white squares of JButtons. So basically my code is something like this:

JButton[][] board = new JButton[8][8];
JPanel boardPanel = new JPanel();
boardPanel.setLayout(new GridLayout(8, 8));
for (row = 0; row < 8; row++) {
    for (col = 0; col < 8; col++) {
        board[row][col] = new JButton("");
        board[row][col].setBackground(new Color(70, 70, 70));
        boardPanel.add(board[row][col]);
    }
}

On the buttons I will have the respective chess pieces. I have them created with a transparent background so they will show on either the black or white squares. When I add them to the buttons, the transparency goes away for but .jpg and .png formats. How can I fix this? Every image is in the following format:

ImageIcon whitePawn = new ImageIcon("whitePawn.jpg");

Thanks!

役に立ちましたか?

解決

JPG does not support transparency. You can use proper PNG files.

There are a few alternative ways though:

  1. You can create 2 images for each piece e.g whitePawnInWhiteCell.jpg and whitePawnInBlackCell.jpg and use them.

  2. You can define Shape for each piece and apply appropriate clip before drawing the image on cell.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top