我的目标是让自定义JComponent在其位置绘制一个矩形,并绘制一个图像(如果有的话)。现在,当我运行代码时,它只绘制sprites / 0.png处的图像,并在左上角绘制两条黑线。它不会绘制任何其他矩形或图像。下面是我的自定义JComponent类:
public class GameSpace extends JComponent {
private static final long serialVersionUID = 1L;
private Image imageAtSpace = null;
public static final int DEFAULT_WIDTH = 100;
public static final int DEFAULT_HEIGHT = 100;
public GameSpace() {
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
public GameSpace(int x, int y) {
this();
setLocation(x, y);
setVisible(true);
}
/*
Other constructors removed for brevity
*/
public void setImage(Image image) {
this.imageAtSpace = image;
}
public void removeImage() {
this.imageAtSpace = null;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.drawRect(getX(), getY(), getWidth(), getHeight());
if (!isEmpty())
g.drawImage(imageAtSpace, getX(), getY(), this);
}
public boolean isEmpty() {
return imageAtSpace == null;
}
}
这是创建面板和JFrame的类:
public class GameView {
JPanel mainGamePanel;
private static final int DEFAULT_NUM_SPOTS = 16;
private static final int SPOTS_PER_ROW = 4;
private static final int SPOTS_PER_COLUMN = 4;
private static final int DEFAULT_WIDTH = GameSpace.DEFAULT_WIDTH;
private static final int DEFAULT_HEIGHT = GameSpace.DEFAULT_HEIGHT;
Map<Integer, GameSpace> gameSpaces = new HashMap<Integer, GameSpace>();
public GameView() {
mainGamePanel = defaultLoad();
}
private JPanel defaultLoad() {
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setFocusable(true);
panel.setSize(400, 400);
int startX =0;
int startY = 0;
for (int i = 0; i < DEFAULT_NUM_SPOTS; i++) {
int xLocation = startX + (i % SPOTS_PER_ROW)*DEFAULT_WIDTH;
int yLocation = startY + (i / SPOTS_PER_COLUMN)*DEFAULT_HEIGHT;
GameSpace gs = new GameSpace(xLocation, yLocation);
gs.setPreferredSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
gs.setImage(new ImageIcon(this.getClass().getResource("/sprites/" + i + ".png")).getImage());
gameSpaces.put(i, gs);
panel.add(gs);
panel.revalidate();
panel.repaint();
}
panel.setVisible(true);
return panel;
}
public static void main(String...args) {
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new GameView().mainGamePanel);
frame.setSize(400, 400);
frame.revalidate();
frame.repaint();
frame.setVisible(true);
}
}
我仍然不确定何时需要重新验证/重新绘制,所以我只是把它扔到任何地方试图解决问题,如果有任何冗余就道歉。任何有关它为什么不绘制带有图像的矩形网格的帮助将不胜感激。即使我注释掉添加图像,它也不会绘制矩形。