我的课程片段扩展了JPanel Board设置在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);
} }
答案 0 :(得分:2)
至少有两件事情很突出......
首先:
private static final String imageFolderPath = "src/resources/images/";
构建应用程序后,目录src
不太可能存在。
第二:
ImageIcon icon = new ImageIcon(imageFolderPath+"/pieces/blank.png");
ImageIcon(String)
表示参考资源是文件系统上的文件。根据{{1}}的值,这似乎不是您的意图。相反,您似乎正在尝试将这些图像用作嵌入式资源,在这种情况下,您应该使用更类似的内容......
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
布局...或其他我们无法识别的内容......