次の図に示すように、上部にボタン パネルを使用するシンプルな GUIGridBagLayout
と、残りのスペースを占めるサイズ変更可能なカスタム コンポーネントがあります。
カスタム コンポーネント (赤いもの) の推奨サイズは (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)
まさに私が望むものですが、フレームのサイズを変更すると、それを超えてしまいます。
注:この関連する質問を見ましたが、私の質問には答えていないようです。