为了更好的参考,我正在做match3(糖果挤压类型)游戏。
public class BoardGraphics extends JPanel {
public static final int WIDTH = 400;
public static final int HEIGHT = 400;
private static final Color COLOR = new Color(0xFF0000); //0xF1E4CB
private final Board board;
public BoardGraphics(Board board){
this.setBackground( COLOR );
this.setSize(HEIGHT, WIDTH);
this.setLayout(new GridLayout(board.getHeight(), board.getWidth(), 0, 0));
this.board = board;
setVisible(true);
drawElements();
}
private void drawElements(){
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
Point p = new Point(i, j);
//Point p = new Point(1, 2);
ImageIcon icon = null;
try {
BufferedImage img = null;
img = ImageIO.read(new File(System.getProperty("user.dir") + "/assets/img/gem_" + board.getElement(p).getTileColor().toString() + ".gif"));
icon = new ImageIcon(img);
JButton btn = new JButton(icon);
btn.setVisible(true);
btn.setOpaque(false);
btn.setContentAreaFilled(false);
btn.setBorderPainted(false);
btn.setSize(50, 50);
if (i == 1) {
btn.setLocation(100, 100); // <- i did this for testing. with this i see 2 gems
}
this.add(btn);
} catch (IOException e) {
e.printStackTrace();
}
}
}
this.revalidate();
this.repaint();
}
}
和这里的jFrame代码:
public class GameGraphics extends JFrame {
private final int WIDTH = 600;
private final int HEIGHT = 800;
private Game game = new Game();
public GameGraphics() {
setTitle("SwitchElements");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(HEIGHT, WIDTH);
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
drawBoard();
}
private void drawBoard(){
// 0xF1E4CB
BoardGraphics board = new BoardGraphics(game.getGameBoard());
System.out.println((WIDTH-BoardGraphics.WIDTH)/2);
board.setLocation( (HEIGHT-BoardGraphics.HEIGHT)/2, (WIDTH-BoardGraphics.WIDTH)/2);
this.add( board );
this.repaint();
}
}
问题是我什么都试过了。但是jButtons并不是按照网格来堆叠的。似乎所有这些都添加到一个位置
"但是jButtons并不是按照网格来堆叠的。似乎所有的按钮都添加到了一个地方"
由于您从未回答过我关于Board
是什么的问题/评论,我将做一个假设。(如果我错了,请纠正我)
看看你的GridLayout
建筑
new GridLayout(board.getHeight(), board.getWidth(), 0, 0)
假设Board
是某种容器,让我们假设维度为300300。
对于GridLayout
构造函数,您说应该有300行和300列。在两个循环中总共只有四次迭代,所以只有4个按钮。布局映射到9000个可用空间。所以,是的,你所有的按钮都将只放在网格的左上角(前四个)位置,其余8996个空格将是最大按钮大小的空格。
要想看到按钮正确添加到网格中,可以做的是向drawElements()
方法传递几个参数,以确保迭代与布局参数相同。
private void drawElements(int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
....
}
然后称之为
public public BoardGraphics(Board board){
int rows = ...
int cols = ...
setLayout(new GridLayout(rows, cols, 0, 0));
drawElements(rows, cols);
此外,您应该避免对组件使用setSize()
和setLocation()
。您应该使用布局管理器,并让他们为您确定的大小和位置。您可以阅读"在容器中布置零部件"以了解有关可用不同布局的更多信息。