[英]Fill GridBagLayout with Array Elements
我正在尝试使用GridBagLayout构建一个包含数组元素的面板。 创建元素工作正常。 问题是要么忽略了Layoutmanager,要么未正确应用约束,无论如何,按钮的排列就好像根本没有Layoutmanager一样。 那我该怎么办呢,看起来像一张桌子?
提前致谢!
旁注:不,不能使用JTable。 在我的应用程序中,实际上仅创建了一些按钮。
编辑:我发现了问题。 我只是忘记了“ setLayout(gbl);”这一行。 愚蠢的我。
//(includes)
public class GUI {
public static void main (String[] args) {
JFrame frame = new JFrame();
frame.add (new MyPanel(5, 4);
frame.setVisible(true);
}
private class MyPanel () extends JPanel {
public MyPanel (int x, int y) {
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout (gbl);
JButton[][] buttons = new JButton[x][y];
for (int i=0; i<x; i++) {
for (int j=0; j<y; j++) {
buttons[i][j] = new JButton("a"+i+j);
gbc.gridx = j; gbc.gridy = i;
gbl.setConstraints(buttons[i][j], gbc);
add (buttons[i][j]);
}
}
}
}
}
您也可以考虑使用MigLayout ,代码更容易维护。
public class MyPanel extends JPanel {
public MyPanel(int x, int y) {
setLayout(new MigLayout("wrap " + x));
JButton[][] buttons = new JButton[x][y];
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
buttons[i][j] = new JButton("a" + i + j);
add(buttons[i][j]);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.