【发布时间】:2014-11-13 18:27:07
【问题描述】:
我正在尝试用JButton 对象制作一个小游戏。我的问题是,当我在面板上添加按钮时,它们没有放在我需要的位置。为了更清楚。
这是我的图片:
这是我的代码:
我的扩展 JFrame 的主类添加了一个新的 Board1 扩展 JPanel
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");
}
}
}
}
【问题讨论】:
-
1) 为了尽快获得更好的帮助,请发布MCVE(最小完整可验证示例)。 2) Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或combinations of them 以及white space 的布局填充和边框。 3) 提供 GUI 预期布局的 ASCII 艺术或简单绘图。
-
从这些数字来看,这可以通过使用 3x3
GridLayout并在中心使用JLabel(作为不可见组件)来实现。 -
我不能使用 GridLayout,因为它是一个特殊的棋盘游戏。而且我不希望我的按钮之间有任何空间,我将添加一个屏幕
-
并且@AndrewThompson 我的代码在发布时正在工作,除了导入!
-
你考虑过使用 GridBagLayout 吗?您可以避免按钮之间的空间,并将一个按钮分布在多个单元格上。
标签: java swing position jbutton layout-manager