Ale*_*ext 1 java layout swing layout-manager flowlayout
我正在做一个原型来展示绘画程序的一些基本功能.现在,这是窗口的样子:

窗口是具有垂直BoxLayout的面板的复合,在其中,有一个自定义图像控件和另一个包含所有按钮的FlowLayout面板.
问题是我必须指定按钮面板的高度(100px).如果我删除该行,则窗口如下所示:

但是,如果我只指定宽度,并为高度写一个0,我得到这个:

我希望布局自己确定按钮面板的正确高度.以下是生成第一个图像的代码:
public void createAndShowGui(){
JFrame.setDefaultLookAndFeelDecorated(true);
setTitle("SimplePaint");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
//Main container layout.
BoxLayout mainLayout = new BoxLayout(getContentPane(), BoxLayout.Y_AXIS);
getContentPane().setLayout(mainLayout);
drawingPanel = new JPanel();
drawingPanel.setLayout(null);
drawingPanel.setPreferredSize(new Dimension(width, height));
TextBox editor = new TextBox();
drawingPanel.add(editor);
editor.setVisible(false);
canvasControl = new DrawableCanvas(editor);
drawingPanel.add(canvasControl);
canvasControl.setBounds(0, 0, width, height);
getContentPane().add(drawingPanel);
drawingSurface = canvasControl.getDrawingSurface();
//Buttons layout.
FlowLayout buttonsLayout = new FlowLayout();
JPanel buttonsPanel = new JPanel(buttonsLayout);
buttonsPanel.setPreferredSize(new Dimension(width, 100)); // <-- Not in this way
//Buttons creation...
pack();
}
Run Code Online (Sandbox Code Playgroud)
提前致谢.
我不知道如何使FlowLayout垂直(不是水平)增长,足以显示所有按钮
FlowLayout不会这样做.
您可以使用Wrap Layout,它扩展FlowLayout并覆盖首选大小方法,以便组件可以自动换行.