我的课堂作品扩展了JPanel
该板设置在GridLayout上。

我的问题是我想在板子的x3 y3上放一块。我添加了它,但看不到它。

这是我的代码:

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.EtchedBorder;

public class Board extends JPanel{
private static final String imageFolderPath = "src/resources/images/";
Dimension dimension = new Dimension(500, 500);
JPanel board;
JLabel piece;
MovePiece mp = new MovePiece(this);

public Board(){
     //set size of panel;
     this.setPreferredSize(dimension);
     this.addMouseListener(mp);
     this.addMouseMotionListener(mp);

  //create the Board
  board = new JPanel();
  board.setLayout(new GridLayout(9,7));
  board.setPreferredSize(dimension);
  board.setBounds(0, 0, dimension.width, dimension.height);
  this.add(board);

  JPanel [][] square = new JPanel[7][9];

  for(int x = 0; x<7; x++){
        for(int y = 0; y<9; y++){
          square[x][y] = new JPanel();
          square[x][y].setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
          square[x][y].setBackground(new Color(185, 156, 107));
          board.add(square[x][y]);
     }
  }

  ImageIcon icon = new ImageIcon(imageFolderPath+"/pieces/blank.png");
  Piece orb =new Piece("Orb", "borb.png", "none", "none", 1, 'b', 0, 3, 7, icon);
  square[3][3].add(orb);


}
}

最佳答案

至少有两件事很突出……

首先:

private static final String imageFolderPath = "src/resources/images/";


构建应用程序后,目录src不太可能存在。

第二:

ImageIcon icon = new ImageIcon(imageFolderPath+"/pieces/blank.png");


ImageIcon(String)表示参考资源是文件系统上的文件。基于imageFolderPath的值,这似乎不是您的意图。相反,似乎您正在尝试将这些图像用作嵌入式资源,在这种情况下,您应该使用更多类似的东西...

ImageIcon icon = new ImageIcon(getClass().getResource("/resources/images/pieces/blank.png"));


就个人而言,我会改用ImageIO,如果图像无法加载,至少会抛出一个IOException ...

try {
    BufferedImage img = ImageIO.read(getClass().getResource("/resources/images/pieces/blank.png"));
    ImageIcon icon = new ImageIcon(img);
    // update UI
} catch (IOException exp) {
    exp.printStackTrace();
    // Probably show a message and exit...
}


奖金问题:

如果没有看到Piece,则可能是由于您没有提供适当的尺寸提示或在其中添加任何内容或使用null布局...或我们无法识别的其他内容...

10-06 13:17