我尝试使用 GridLayout
多次将 JButton
添加到我的 JPanel
。但出于某种原因,每次我运行程序时它只显示 1 个按钮。
代码如下:
jPLeft = new JPanel();
jPLeft.setPreferredSize(new Dimension(600,500));
jPLeft.setBackground(Color.WHITE);
jPLeft.setLayout(new GridLayout(2,2));
jPLeft.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
window.add(jPLeft, BorderLayout.CENTER);
imageSand = new ImageIcon("..\\CSY1020\\src\\resources\\sand.jpg");
jBSand = new JButton(imageSand);
jPLeft.add(jBSand);
jPLeft.add(jBSand);
jPLeft.add(jBSand);
jPLeft.add(jBSand);
最佳答案
一个Component
只能添加一次,并且只能有1个parent Container
imageSand = new ImageIcon("..\\CSY1020\\src\\resources\\sand.jpg");
for (int i = 0; i < 4; i++) {
JButton jBSand = new JButton(imageSand);
jPLeft.add(jBSand);
jPLeft.add(jBSand);
jPLeft.add(jBSand);
jPLeft.add(jBSand);
}
关于java - GridLayout 在 JPanel 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28370141/