我是摇摆新手,我想设计一个我所附类型的屏幕。右边的大面板使用卡片布局,在各种按钮点击时显示。我不知道如何排列组件,例如我有 6 列,并且随着我添加更多组件,行数会增加。如果有人能给我一个关于我需要使用哪种布局或如何完成它的伪代码的想法,我将不胜感激。
万分感谢 !!!
更新:伙计们,我现在已经将我的解决方案移动到每个使用 MigLayout。它非常简单,并且在动态组件放置的情况下非常易于使用。非常感谢您宝贵的时间和答案。
GridLayout
非常适合这个:GridLayout(int rows,int cols)
。的值0
将指定行/列可以随着您添加更多组件而增长。
来自 Oracle 的简短示例:
GridLayout experimentLayout = new GridLayout(0,2);//create grid any amount of rows and 2 coloumns
...
compsToExperiment.setLayout(experimentLayout);//add gridlayout to Component/JPanel
compsToExperiment.add(new JButton("Button 1"));
compsToExperiment.add(new JButton("Button 2"));
compsToExperiment.add(new JButton("Button 3"));
compsToExperiment.add(new JButton("Long-Named Button 4"));
compsToExperiment.add(new JButton("5"));
更新:
但是,如果您需要更灵活的网格布局,请参阅GridBagLayout
Guillaume Polet 建议:
如您所见,它允许您使用每个组件超过 1 行/列:
JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if (shouldFill) {
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
}
button = new JButton("Button 1");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
pane.add(button, c);
button = new JButton("Button 2");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
pane.add(button, c);
button = new JButton("Button 3");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 2;
c.gridy = 0;
pane.add(button, c);
button = new JButton("Long-Named Button 4");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40; //make this component tall
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
pane.add(button, c);
button = new JButton("5");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0; //reset to default
c.weighty = 1.0; //request any extra vertical space
c.anchor = GridBagConstraints.PAGE_END; //bottom of space
c.insets = new Insets(10,0,0,0); //top padding
c.gridx = 1; //aligned with button 2
c.gridwidth = 2; //2 columns wide
c.gridy = 2; //third row
pane.add(button, c);
看看GroupLayout或GridBagLayout。前者可能比后者更容易使用。