gpt4 book ai didi

java - 如何使用 GridBagLayout 设置最小尺寸?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:16:31 25 4
gpt4 key购买 nike

我有一个使用 GridBagLayout 的简单 GUI,顶部有一个按钮面板,一个自定义可调整大小的组件占据了剩余空间,如下图所示:

The GUI at start-up.

自定义组件(红色组件)的首选大小为 (400, 300),最小大小为 (40, 30),并且很乐意将大小调整为大于该大小的任何大小。但是,我希望我的框架尊重按钮面板的最小尺寸,并且不允许调整框架的大小,以致任何按钮都不会完全显示在屏幕上。这不是当前的行为,因为我可以将其调整到远远超过此处所见的这些边界:

The GUI resized ridiculously small.

我目前的代码如下:

import javax.swing.*;
import java.awt.*;

public class Example {
public static void main(String[] args) {
// Setup JFrame and GridBagLayout.
JFrame frame = new JFrame("Example");
Container contentPane = frame.getContentPane();
GridBagLayout layout = new GridBagLayout();
contentPane.setLayout(layout);
layout.rowWeights = new double[] {0.0, 1.0};
layout.columnWeights = new double[] {1.0};
GridBagConstraints cons = new GridBagConstraints();

// Add button panel with a BoxLayout.
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));
cons.anchor = GridBagConstraints.NORTHWEST;
cons.gridx = 0;
cons.gridy = 0;
layout.setConstraints(panel, cons);
contentPane.add(panel);

// Add custom component, resizable.
JComponent custom = new JComponent() {
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}

public Dimension getMinimumSize() {
return new Dimension(40, 30);
}

public void paintComponent(Graphics g) {
g.setColor(Color.RED);
g.fillRect(0, 0, getWidth(), getHeight());
}
};
cons.gridx = 0;
cons.gridy = 1;
cons.fill = GridBagConstraints.BOTH;
layout.setConstraints(custom, cons);
contentPane.add(custom);

// Pack and show frame.
frame.pack();
frame.setVisible(true);
}
}

我已经在 Mac OS X 10.8 (Java 6) 和 Ubuntu 3.2.8 (Java 6) 上对此进行了测试,并观察到了同样的事情。

如何防止框架调整大小以覆盖任何按钮?更一般地说,如何让 GridBagLayout 真正遵守我的组件的最小尺寸?当我打印出框架的最小尺寸时,我得到了 (291, 81),这正是我想要的,但是当我调整框架大小时,它超出了这个范围。

注意:我看过this related question但它似乎没有回答我的问题。

最佳答案

我不确定为什么,但是如果我使用...

frame.setMinimumSize(frame.getMinimumSize());

创建 UI 后(显然),它就可以工作了。

我“认为”它与 ((WindowPeer)peer).updateMinimumSize(); 有关在setMinimumSize Window的尺寸法| ...

关于java - 如何使用 GridBagLayout 设置最小尺寸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19507479/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com