gpt4 book ai didi

java - 国际象棋分层问题

转载 作者:行者123 更新时间:2023-12-01 14:38:47 25 4
gpt4 key购买 nike

我对 Java 还很陌生,我决定尝试用 Swing 制作一个国际象棋游戏。我知道我的程序效率极低,但这并不是我的问题。我的问题是,添加 JButton 后我无法查看白色 pawn 的图像,但如果我在添加按钮之前添加添加 pawn JLabel 的代码,我可以看到 pawn。为此,我认为问题出在我的分层问题上,并尝试用 LayeredPanes 替换面板,但没有成功。

基本上,我想要发生的是让 JButton 和 JLabel 都显示在同一个方 block 中并保持按钮可单击。另外,我真的不想合并任何新的导入,而只使用 JButtons、JLabels 等。抱歉,如果我的解释有点令人困惑,请提前致谢。这是我的代码:

private JFrame frame = new JFrame();
private JPanel[][] square = new JPanel[8][8];
private JButton[][] squareB = new JButton[8][8];
private JPanel blank[] = new JPanel[6];
private JButton newGame = new JButton("New Game");
private JButton exitGame = new JButton("Exit");

ArrayList <Chess> pieces = new ArrayList<Chess>();
ChessGame() throws IOException
{

frame.setLayout(new GridLayout(9,8));
frame.setSize(800,900);
for(int x=0; x<8; x++)
{
for(int y=0; y<8; y++)
{
square[x][y] = new JPanel();
square[x][y].setSize(100,100);
}
}

for(int y=0; y<8; y++)
{
for(int x=0; x<8; x++)
{
frame.add(square[x][y]);
if(y%2==0)
if(x%2==0)
square[x][y].setBackground(Color.cyan);
else
square[x][y].setBackground(Color.blue);
else
if(x%2==0)
square[x][y].setBackground(Color.blue);
else
square[x][y].setBackground(Color.cyan);
}
}
for(int x=0; x<8; x++)
{
for(int y=0; y<8; y++)
{
squareB[x][y] = new JButton();
squareB[x][y] = new Chess(x,y);
square[x][y].add(squareB[x][y]);
squareB[x][y].setSize(square[x][y].getSize());
squareB[x][y].setMargin(new Insets(0, 0, 100, 100));
squareB[x][y].setContentAreaFilled( false );
squareB[x][y].setOpaque(false);
squareB[x][y].setContentAreaFilled(false);
squareB[x][y].setBorderPainted(false);
squareB[x][y].addActionListener(this);
}
}
for(int x=0; x<6; x++)
{
blank[x] = new JPanel();
frame.add(blank[x]);
if(x==2)
{
frame.add(newGame);
frame.add(exitGame);
}
}

JLabel WPawn = new JLabel(new ImageIcon(((new ImageIcon("C:\\Users\\Matthew\\Desktop\\Chess Pieces\\WPawn.png")).getImage()).getScaledInstance(80, 83, java.awt.Image.SCALE_SMOOTH)));
squareB[1][1].add(WPawn);

newGame.addActionListener(this);
exitGame.addActionListener(this);
frame.setVisible(true);
}
public static void main(String[] args) throws IOException
{
new ChessGame();
}

最佳答案

不要尝试将 JLabel 添加到没有布局管理器的 JButton,而是设置 JButton 的图标

Image WPawn = new ImageIcon(ImageIcon("C:\\Users\\Matthew\\Desktop\\Chess Pieces\\WPawn.png").getImage().getScaledInstance(80, 83, java.awt.Image.SCALE_SMOOTH));
squareB[1][1].setIcon(WPawn);

您可能想仔细看看 How to use Buttons

Ps我还推荐ImageIO通过 ImageIcon 读取图像

关于java - 国际象棋分层问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16204653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com