解决了:
在尝试制作 SSCCE 之后,才发现问题出在哪里。
它与我的单元类有关,我没有意识到我正在覆盖 JComponent 类中的 getX() 和 getY()。
重命名这些访问器后,一切都按预期工作
=========================================
我有一个 GridLayout 设置为 3 行 x 3 列的 JPanel。
我正在尝试将 JPanel 添加到网格布局中的每个单元格以填充所有 9 个单元格。这些 JPanel 中的每一个都有一个覆盖的 paintChildren 方法,该方法将从 JPanel 的左上角开始绘制某种矩形 - 最终结果将是每个单元格中都有一个从单元格的左上角开始的矩形。
将所有 JPanel 添加到 gridlayout 后,它们都出现在左上角相互重叠(我已经确认它们是重叠的),而不是布置在 3x3 网格中。
我怎样才能让它们排列在 3x3 网格中?
(简化)代码:
public class Panel extends JPanel {
public Panel(int x, int y) {
layout = new GridLayout(x, y, 2, 2);
setLayout(layout);
populateGrid();
}
public void populateGrid() {
removeAll();
for (int i = 0; i < 9; i++)
add(new Cell(50,50));
}
}
public class Cell extends JPanel {
public Cell(int x, int y) {
// x/y values used to define rectangle
setBorder(BorderFactory.createLineBorder(new Color(0,0,0)));
setBackground(Color.WHITE);
}
public void paintChildren(Graphics g) {
g.setColor(Color.BLUE);
g.fillRect(0, 0, x, y);
}
}