我有一个使用GridBagLayout的简单GUI,顶部有一个按钮面板,而一个自定义可调整大小的组件占用了其余的空间,如下图所示:
定制组件(红色组件)的首选大小为(400,300),最小大小为(40,30),并且很高兴将其调整为更大的大小.
但是,我希望我的框架遵守按钮面板的最小尺寸,并且不允许调整框架的大小,以使任何按钮都不能完全显示在屏幕上.这不是当前的行为,因为我可以将其调整为远远超出这些边界的大小,如下所示:
我当前的代码如下:
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),这正是我想要的,但是当我调整框架的尺寸时,它超出了这个范围.