java - Swing 屏设计,哪种Layout?

标签 java swing layout

我是 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/

相关文章:

html - CSS 百分比布局丢失

android - 您必须在某些设备中提供layout_width属性

android - 从 RelativeLayout 或 Group Drawables 中获取 Drawables

javascript - 使用 Java Selenium JavascriptExecutor 访问 AngularJS 变量

java - 在构造函数内部或外部设置字段有区别吗?

java - JTable - 如何获取已删除的行

java - slider 监听器循环中的 JTextField

java - 当 JFrame 移动到桌面前面时会触发什么 Swing 事件

java - 使用 Spring 作为 grails 前端的后端

java - 同一 Web 应用程序的多个服务器(需要任何先验配置吗?)