我的 GridBagLayout 遇到一些问题。我创建了一个 JPanel(在本例中称为 mainPanel),其布局已设置为 GridBagLayout。我已经为每个 JButton 指定了约束,并将约束添加到每个按钮。现在,当我运行代码时,按钮始终彼此相邻,无论我在约束中指示的 gridx/gridy 值如何。此外,当我希望一个按钮出现在右上角、左上角和南边时,按钮始终位于 JFrame 的中心。
import javax.swing.*;
import java.awt.*;
public class test {
public static void main (String[] args) {
myJFrame test = new myJFrame();
}
}
class myJFrame extends JFrame {
public myJFrame () {
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel myPanel = new mainPanel();
add(myPanel);
setVisible(true);
}
}
class mainPanel extends JPanel {
public mainPanel(){
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.NORTHWEST;
c.gridx = 1000;
c.gridy= 1;
add(new JButton("1"),c);
c.anchor = GridBagConstraints.NORTHEAST;
c.gridx = 100;
c.gridy= 1;
add(new JButton("2"),c);
c.anchor = GridBagConstraints.SOUTH;
c.gridx = 200;
c.gridy= 1;
add(new JButton("3"),c);
}
}
最佳答案
Now, when I run my code, the buttons are always next to each other, irrespective of the gridx/gridy value that I indicate in the constraints.
正确,您不能只指定随机单元格。每个单元格中必须有一个组件。
Furthermore, the buttons are always at the center of the JFrame,
是的,如果您不指定weightx/weighty约束,这是默认行为。
阅读 Swing 教程中关于 How to Use GridBagLayout 的部分有关约束和工作示例的更多信息。
为什么要随机选择 x 个位置,例如 100、200、1000?也许水平的 BoxLayout 会是更好的布局管理器。您可以添加组件,然后在它们之间添加空间:
panel.add( button1 );
panel.add( Box.createHorizonalStrut(100);
panel.add( button2 );
panel.add( Box.createHorizonalStrut(200);
或者可以使用 FlowLayout 并指定每个组件之间的“间隙”。
关于java - 当我将 GridBagLayout 添加到 JFrame 时,它不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36799170/