【问题标题】:How to make compact grid with resizable JButtons?如何使用可调整大小的 JButton 制作紧凑的网格?
【发布时间】:2012-03-19 13:32:49
【问题描述】:

我正在尝试重用 Swing SpringLayout 紧凑网格功能来制作可调整大小的 JButton 的紧凑网格,使用: http://docs.oracle.com/javase/tutorial/uiswing/layout/spring.html

它工作正常,但 SpringLayout 无法调整 JButtons,所以对我来说没用。 有没有其他方法可以创建一个带有可调整大小的 Jbuttons 的紧凑网格?

【问题讨论】:

  • 使用GridLayout,使用GridBagLayout,编写自己的LayoutManager。
  • 我尝试使用 GridLayout 和 GridBagLayout。他们的问题是所有列的列宽都相同。
  • 如何编写自己的 LayoutManager?
  • 您为什么(选择一个)a)使用不适合手动使用的 LayoutManager b)在自定义实现中重新发明轮子?看看强大的第三方管理器,例如 FormLayout、MigLayout、DesignGridLayout

标签: java swing layout


【解决方案1】:
A: Use GridLayout, use GridBagLayout, write your own LayoutManager.
Q: How can I write my own LayoutManager?

请不要,对于像 @StanislavL 这样的 Swing Guru 来说,编写自己的 LayoutManager 并不复杂,因为我们其他人最好使用 MigLayoutGridBagLayout

【讨论】:

    【解决方案2】:

    您可以为此使用 GridBagLayout。这是一个示例,其中显示了两个按钮 - 一个保持其宽度,另一个在调整框架大小时改变其宽度。

    注意 GridBagConstraints 告诉组件它在布局中应该如何表现。权重控制调整大小的行为。更多信息请访问Java Tutorials

    package test;
    
    import java.awt.Button;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    
    import javax.swing.JFrame;
    
    public class LayoutResizeButtonTest extends JFrame {
    
        public static void main(String[] args) {
    
            LayoutResizeButtonTest app = new LayoutResizeButtonTest();
    
            app.setDefaultCloseOperation(EXIT_ON_CLOSE);
            app.setVisible(true);
    
        }
    
        LayoutResizeButtonTest() {
    
            this.setLayout(new GridBagLayout());
    
            GridBagConstraints c = new GridBagConstraints();
            c.fill = GridBagConstraints.HORIZONTAL;
            c.weightx = 1.0;
    
            this.add(new Button("Resizable"), c);
    
            c = new GridBagConstraints();
            c.weightx = 0.0;
    
            this.add(new Button("Not Resizable"));
    
            this.pack();
    
        }
    
    }
    

    【讨论】:

    • 但是如何使用 GridBagLayout 创建紧凑的网格?
    • @user1253040 “紧凑网格”是什么意思?
    • 在 GridBagLayout 中,列中的每个组件都具有相同的宽度——所有列的最大宽度。紧凑网格意味着列宽是列中的最大组件宽度。
    猜你喜欢
    • 1970-01-01
    • 2016-02-29
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    相关资源
    最近更新 更多