gpt4 book ai didi

java - Swing 屏设计,哪种Layout?

转载 作者:行者123 更新时间:2023-12-02 04:38:50 24 4
gpt4 key购买 nike

我是 swing 新手,我想设计一个我所附加类型的屏幕。右侧大面板使用卡片布局,单击各种按钮即可显示。我不知道如何排列组件,例如我有 6 列,并且随着添加更多组件,行数也会增加。如果有人能让我了解我需要使用哪种布局或需要如何完成它的伪代码,我将不胜感激。

非常感谢!!!

enter image description here

更新:伙计们,我现在已将每个解决方案移至使用 MigLayout。它非常简单,并且在动态组件放置的情况下非常容易使用。感谢大家的宝贵时间和解答。

最佳答案

GridLayout非常适合这个:GridLayout(int rows,int cols) 。值 0 将指定行/列可以随着您添加更多组件而增长。

来自 Oracle 的简短示例:

enter image description here

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正如纪尧姆·波莱特建议的那样:

enter image description here

如您所见,它允许您在每个组件中使用超过 1 行/列:

enter image description here

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);

关于java - Swing 屏设计,哪种Layout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12569587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com