Java Swing设置JPanel大小

cob*_*bie 2 java layout swing layout-manager

任何人都可以指出我在这个java swing gui代码出错的地方.我试图将两个按钮添加到JPanel,然后在设置大小后将其添加到框架中,但似乎没有响应setSize传递给它的值

public Test() {
    GridLayout layout = new GridLayout(1, 2);
    //this.setLayout(layout);
    this.setSize(700, 700);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    buttonPanel = new JPanel();
    buttonPanel.setSize(new Dimension(30, 100));

    JButton rectButton = new JButton("Rectangle");
    JButton ovalButton = new JButton("Oval");
    buttonPanel.add(rectButton);
    buttonPanel.add(ovalButton);
    this.add(buttonPanel);
    this.add(new PaintSurface());
    this.setVisible(true);  
}
Run Code Online (Sandbox Code Playgroud)

Mad*_*mer 6

这可能无法回答您的直接问题......但......

GridLayout layout = new GridLayout(1, 2);
this.setLayout(layout);
// You're original code...
// Why are you using `BorderLayout.CENTER` on a `GridLayout`
this.add(new PaintSurface(), BorderLayout.CENTER);
Run Code Online (Sandbox Code Playgroud)

您将布局设置为a GridLayout,但是您使用BorderLayout约束来应用其中一个组件?

此外,请确保没有调用Test#pack代码中的else,因为这将覆盖其值setSize

更新(从更改到问题)

请记住,默认布局管理器JFrameBorderLayout,所以即使你正在调用buttonPanel.setSize,它很可能会被布局管理器重新开始覆盖.

我将阅读布局管理器的可视指南使用布局管理器来查找最符合您要求的布局管理器.

如果找不到单个布局管理器,请考虑使用具有不同布局管理器的复合组件,使布局更接近您想要实现的布局.