【问题标题】:Java chess board image not showingJava 棋盘图像未显示
【发布时间】:2014-03-25 00:34:24
【问题描述】:

我正在开发一个棋盘,但有一个问题。我正在尝试使用图像来表示棋盘。但是图像没有显示。

这是有问题的代码:

//Add a chess board to the Layered Pane 
chessBoard = new JPanel();
layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER);
chessBoard.setLayout( new GridLayout(8, 8) );
chessBoard.setPreferredSize( boardSize );
chessBoard.setBounds(0, 0, boardSize.width, boardSize.height);

for (int i = 0; i < 64; i++) {
JPanel square = new JPanel( new BorderLayout() );
chessBoard.add( square );

int row = (i / 8) % 2;
if (row == 0); 
JLabel panel = new JLabel(new ImageIcon("/Users/Downloads/pieces/EmptySquare.jpg") ); 
}

所有显示的都是碎片,没有正方形,在此先感谢。

【问题讨论】:

  • 我不认为"/Users/Downloads/pieces/EmptySquare.jpg" 是真正的路径。没有驱动器?
  • 路径不是问题,我不得不编辑问题中的路径,因为它部分包含我的名字。
  • 我知道,只是指出来。问题是您没有对JLabel 做任何事情。

标签: java swing chess


【解决方案1】:

两件事...

首先...

您的if 语句以; 结尾

if (row == 0); 

这实际上完全忽略了该声明。

其次,您似乎从未将 panel 添加到 UI...

    //...
    JLabel panel = new JLabel(new ImageIcon("/Users/Downloads/pieces/EmptySquare.jpg") ); 
} // End of for-loop...

考虑使用ImageIO.read 而不是ImageIcon,因为如果无法加载图像,它将提供更多详细信息。更多详情请查看Reading/Loading an Image...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-10
    • 2020-12-12
    • 2017-09-03
    • 2011-04-02
    • 2011-11-19
    相关资源
    最近更新 更多