0

可能重复:
JButton 上的 ImageIcon 未显示在 Runnable JAR 文件中

我正在尝试将图像添加到 java 中的 gui 以进行国际象棋游戏:

JPanel theBoard;
    JLabel aPiece;
    JLayeredPane layeredPane;

    public ChessGameGUI() 
    {
        Dimension size = new Dimension(480, 480);

        layeredPane = new JLayeredPane();
        getContentPane().add(layeredPane);
        layeredPane.setPreferredSize(size);

        theBoard = new JPanel();
        layeredPane.add(theBoard, JLayeredPane.DEFAULT_LAYER);
        GridLayout chessBoardLayout = new GridLayout(8,8);
        theBoard.setLayout(chessBoardLayout);
        theBoard.setPreferredSize(size);
        theBoard.setBounds(0, 0, size.width, size.height);

        boolean drawWhite = false;

        // setup initial squares
        for(int x = 0; x < 8; x++)
        {
            for(int y = 0; y < 8; y++)
            {
                BorderLayout squareBorder = new BorderLayout();
                JPanel aChessSquare = new JPanel(squareBorder);
                theBoard.add(aChessSquare);

                if(drawWhite) aChessSquare.setBackground(Color.white);
                else aChessSquare.setBackground(Color.green);

                if(y == 7);
                else drawWhite = !drawWhite;
            }
        }
    }

这段代码很好地设置了方格图案板,但是当我去添加单独的部分时,什么也没有发生:

for(int x = 0; x < 8; x++)
        {
            for(int y = 0; y < 8; y++)
            {
                if(board[x][y]._isOccupied)
                {
                    System.out.println("found a piece at x = " + x + " y = " + y);

                    //ImageIcon pieceImage = new ImageIcon("Images/wPawn.jpg");
                    ImageIcon pieceImage = findPieceImage(board, x, y);

                    JLabel pieceToDraw = new JLabel(pieceImage);
                    JPanel curComponent = (JPanel)theBoard.getComponent(7 * x + y);
                    curComponent.add(pieceToDraw);
                }
            }
        }

图片文件夹包含在 src 文件夹中。任何人都知道为什么这不起作用?

4

0 回答 0