我想制作最大宽度受限的面板,但是当容器变短时会减小其宽度。
我使用过GridBagLayout
,但当尺寸变得足够短时,它的行为很奇怪。
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
* @author Michael Nesterenko
*
*/
public class SSCE extends JFrame {
/**
*
*/
public SSCE() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gbl = new GridBagLayout();
gbl.columnWidths = new int[] {200, 1};
gbl.columnWeights = new double[] {0, 1};
gbl.rowHeights = new int[] {10};
gbl.rowWeights = new double[] {0};
setLayout(gbl);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
JPanel sizeRestrictedPanel = new JPanel();
sizeRestrictedPanel.setBackground(Color.BLUE);
sizeRestrictedPanel.setMinimumSize(new Dimension(50, 50));
sizeRestrictedPanel.setMaximumSize(new Dimension(300, 50));
sizeRestrictedPanel.setPreferredSize(new Dimension(300, 50));
add(sizeRestrictedPanel, gbc);
JPanel dummy = new JPanel();
dummy.setBackground(Color.RED);
add(dummy, gbc);
setPreferredSize(new Dimension(600, 200));
pack();
}
/**
* @param args
*/
public static void main(String[] args) {
new SSCE().setVisible(true);
}
}
当框架宽度变得足够短时,蓝色面板会立即调整大小,但是我希望它可以通过窗口大小调整平滑地调整大小。