【发布时间】:2013-04-25 00:48:41
【问题描述】:
我是 Java 新手,我决定尝试使用 Swing 制作国际象棋游戏。 我知道我的程序效率极低,但这并不是我的问题。 我的问题是,在添加 JButton 后我无法查看白棋的图像,但如果我在添加按钮之前添加代码以添加棋子 JLabel,我可以看到棋子。由于这个原因,我认为问题是我有分层问题,我尝试用 LayeredPanes 替换面板并没有任何成功。
基本上,我想要让 JButton 和 JLabel 都显示在同一个方块中并保持按钮可点击。 此外,我真的不想合并任何新的导入,而只使用 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();
}
【问题讨论】:
-
若想尽快获得更好的帮助,请发布SSCCE.. 仅包含几颗棋子。
-
我知道这有点傻,但我有点想使用 JButtons。这不可能吗?
-
这只是 JButton 和 JPanel,没有 Chess Pieces。就像我说的那样,效率很低。