我想为具有< = 3列和可变数量的行的布局使用GridBagLayout(如果有人知道另一个布局可以轻松做到这一点,请告诉我),每当我按下“添加”按钮,一个方块就会被添加到第一个可用的位置。像这样:GridBagLayout添加后不要让组件“跳”
|x x x|
|x x x|
|x o |
x的是正方形,当我按下添加一个新的正方形应该加上o现在。 我设法“之类的使它的工作”,例如:
public void addSquare(Square square) {
c.fill = GridBagConstraints.NONE;
c.gridx = nrOfSquares % 3;
c.gridy = (int) (nrOfSquares/3);
c.weighty = 1;
c.weightx = 1;
c.anchor = GridBagConstraints.NORTHWEST;
c.insets = new Insets(5, 5, 5, 5);
this.container.add(square, c);
this.container.revalidate();
++nrOfSquares;
}
的问题是,第二方阵我添加添加这样的:
|x x |
请注意,有一个额外的空间在第一个广场和第二个广场之间。添加额外行时,我遇到同样的问题。
现在我该如何解决我的代码,使广场不“跳”,并像我给第一个例子一样添加?
编辑:根据要求,一个更好的例子后,我将它转换为常规网格布局:
public class Square extends JPanel {
public Square() {
super();
Dimension SIZE = new Dimension(200, 200);
this.setSize(SIZE);
this.setPreferredSize(SIZE);
this.setMinimumSize(SIZE);
this.setMaximumSize(SIZE);
this.setBackground(Color.ORANGE);
this.setVisible(true);
}
}
public class SquareContainer extends JPanel {
protected JPanel realContainer;
public SquareContainer(int width, int height) {
super();
this.setLayout(new BorderLayout());
this.setBackground(Color.WHITE);
this.setSize(width, height);
this.realContainer = new JPanel();
GridLayout layout = new GridLayout(0, 3);
layout.setHgap(10);
layout.setVgap(10);
this.realContainer.setLayout(layout);
this.realContainer.setBackground(this.getBackground());
JScrollPane scroller = new JScrollPane(this.realContainer);
scroller.getVerticalScrollBar().setUnitIncrement(20);
this.add(scroller, BorderLayout.CENTER);
}
public void addSquare(Square square) {
this.realContainer.add(square);
this.realContainer.revalidate();
}
}
我只想补充一点,到一个JFrame:
public class TheGreatFrame extends JFrame {
public TheGreatFrame() {
super();
this.setSize(800, 800);
this.setLocationRelativeTo(null);
this.setLayout(new BorderLayout());
this.setResizable(false);
this.add(new SquareContainer(750, 660), BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setVisible(true);
}
}
为什么不只是一个'GridLayout(0,3)'(3列,可变行数)? –
好的,这样可以毫无问题地工作吗? – teuneboon
它可以,取决于你想要它做什么。 :) –