我正在尝试用 JButton
对象制作一个小游戏。我的问题是,当我向面板添加按钮时,它们没有放在我需要的位置。更清楚。
这是我的图片:
这是我的代码:
我扩展 JFrame
的主类添加了一个扩展 JPanel
的新 Board1
public class Main2 extends JFrame {
public Main2() {
setVisible(true);
setSize(500, 500);
add(new Board1());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setTitle("Zombicide");
setResizable(false);
}
public static void main(String[] args) {
new Main2();
}
}
我的 Board 类扩展了 JPanel
并添加了一些扩展 JButton
的 Zone
对象。
public class Board1 extends JPanel implements Board {
private List<Zone> zones = new ArrayList<Zone>();
public Board1() {
zones.add(new Zone(1, false, true, null, "/zone1D1C.jpg", 0, 0, this));
zones.add(new Zone(2, false, false, null, "/zone2D1C.jpg", 150, 0, this));
zones.add(new Zone(3, false, false, null, "/zone3D1C.jpg", 300, 0, this));
zones.add(new Zone(4, true, false, null, "/zone4D1C.jpg", 0, 150, this));
zones.add(new Zone(5, false, false, null, "/zone5D1C.jpg", 300, 150, this));
zones.add(new Zone(6, true, false, null, "/zone6D1C.jpg", 0, 300, this));
zones.add(new Zone(7, true, false, null, "/zone7D1C.jpg", 150, 300, this));
zones.add(new Zone(8, false, false, null, "/zone8D1C.jpg", 300, 300, this));
}
}
最后是扩展 JButton
public class Zone extends JButton implements ActionListener {
private final Zone zone;
private final Board board;
private Integer id;
private boolean piece;
private boolean egout;
private Integer x;
private Integer y;
private Integer x_end;
private Integer y_end;
public Zone(Integer id, boolean piece, boolean egout, Dalle[] dalles, List<Connexion> connexions, String image_name, Integer x, Integer y, Board board) {
zone = this;
addMouseListener(new TAdapter());
this.board = board;
this.piece = piece;
this.egout = egout;
this.id = id;
this.setLayout(null);
this.setBorder(null);
this.setText(null);
ImageIcon ii = new ImageIcon(this.getClass().getResource(image_name));
this.setIcon(ii);
this.x = x;
this.y = y;
this.setBounds(x, y, ii.getIconWidth(), ii.getIconHeight());
this.x_end = x + ii.getIconWidth();
this.y_end = y + ii.getIconHeight();
this.setSize(ii.getIconWidth(), ii.getIconHeight());
}
private class TAdapter extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent e) {
if (gotoZone()) {
...
} else {
System.out.println("error");
}
}
}
}
最佳答案
GridBagLayout
是最适合您尝试实现的布局。它可能是这样的:
public class Board1 extends JPanel implements Board {
public Board1() {
super();
this.setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 0;
this.add(new Zone(...), constraints);
constraints.gridx = 1;
constraints.gridy = 0;
this.add(new Zone(...), constraints);
// You caught the point I think
}
}
Oracle 制作的教程很好here .
关于java - Swing - 定位一些 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26905027/