【问题标题】:JPanel GridLayout make all buttons be in same placeJPanel GridLayout 使所有按钮都在同一个地方
【发布时间】:2016-05-08 21:46:48
【问题描述】:

我为我的学校创建了一些应该包含n*n 按钮的程序。 按钮应采用矩阵布局,具有 n 行和 n 列。

所以我创建了面板,并创建了一个名为 Position 的类,它扩展了 JButtons - 我想要添加到面板的按钮。

我在面板中添加了布局:

this.setLayout(new GridLayout(n,n));

然后我创建 n*n Positions 按钮并将它们添加到面板中。

问题是,所有按钮都添加到同一个位置(屏幕左上角)——即使我可以在它们应该在的位置单击它们! (见屏幕截图,其中 n 为 4)

即使按钮不存在,我也可以点击灰色区域(空白):

]1

面板构造函数:

    public GamePanel(int n) {
    super();
    this.n = n;
    positions = new Position[n][n];
    this.setLayout(new GridLayout(n,n));
    currX = new Random().nextInt(n);
    currY = new Random().nextInt(n);

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            Position p = new Position(i, j);
            this.add(p);
            positions[i][j] = p;
        }
    }

Position类的构造函数:

public class Position extends JButton {
private int x;
private int y;
private boolean visited = false;

public Position(int x, int y) {
    super("");
    this.x = x;
    this.y = y;
    this.setPreferredSize(new Dimension(50,50));
}

框架:

public class Game extends JFrame {
private GamePanel gamePanel;
public Game(int n){
    super();
    gamePanel = new GamePanel(n);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(new BorderLayout());
    this.add(gamePanel,BorderLayout.CENTER);
    this.add(new JTextField(),BorderLayout.NORTH);
    this.pack();
    this.setVisible(true);
}

}

我的错误在哪里?

【问题讨论】:

  • 不要将您的代码发布为图像。它应该是文本。
  • 我想显示程序结果,我也写成文本
  • 这样可以正常添加一个普通的JButton。你能显示Position类的构造函数的代码吗?
  • 是的,我添加了位置类的代码
  • 您是否覆盖了JButtongetXgetY 方法以返回您的x/y 值?

标签: java swing layout jpanel jbutton


【解决方案1】:

所以,在把你不完整的例子重新组合起来之后,我得到了......

然后我注意到Position 按钮中的x/y 属性,这让我觉得你可能已经包含了getXgetY 方法,比如...

public class Position extends JButton {

    private int x;
    private int y;
    private boolean visited = false;

    public Position(int x, int y) {
        super("");
        this.x = x;
        this.y = y;
        this.setPreferredSize(new Dimension(50, 50));
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }


}

生成...

所以答案是,包含一个完整的 runnable example 来证明您的问题。这不是代码转储,而是您正在做的事情的一个例子,它突出了您遇到的问题。这将减少混乱并获得更好的响应

并且不要覆盖JButtongetXgetY,而是将方法更改为getGridXgetGridY之类的东西

【讨论】:

    猜你喜欢
    • 2014-12-20
    • 1970-01-01
    • 2017-04-08
    • 2019-08-21
    • 1970-01-01
    • 2022-10-18
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    相关资源
    最近更新 更多