【问题标题】:How to change the size of the JButton?如何更改 JButton 的大小?
【发布时间】:2014-11-15 21:57:46
【问题描述】:

这是我的代码。该按钮的大小与FlowLayout 相同。如何使按钮变小?

public class javalearning extends JFrame{{

    FlowLayout f = new FlowLayout();
    this.setSize(600,600);

    JFrame j = new JFrame();
    this.setTitle("this is a tittle");

        JButton button = new JButton();
        button.setText("Button");
        this.add(button);
        button.setBounds(10, 10, 10, 10);

        this.setVisible(true);  
    }
}

【问题讨论】:

    标签: java swing jbutton layout-manager flowlayout


    【解决方案1】:

    我想你忘了setLayout,当我这样做时它工作正常。不要使用setBounds 并把它放在javalearning 构造函数中,我也建议你setDefaultCloseOperation 喜欢

    public javalearning() {
        FlowLayout f = new FlowLayout();
        this.setLayout(f);
        this.setSize(600, 600);
        this.setTitle("this is a tittle");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JButton button = new JButton();
        button.setText("Button");
        this.add(button);
        // button.setBounds(10, 10, 10, 10);
    
        this.setVisible(true);
    }
    
    public static void main(String[] args) {
        javalearning m = new javalearning();
    }
    

    最后,按照惯例,Java 类名以大写字母开头,并且是驼峰式。像JavaLearning 这样的东西会遵循这个约定。

    【讨论】:

    • (咳嗽)setBounds(咳嗽)
    • @MadProgrammer 哎呀。错过了。谢谢!
    • 它只会混淆代码,否则它的方向是正确的;)
    【解决方案2】:

    您从未将布局管理器 (FlowLayout) 设置为框架,因此 JFrame 仍在使用其默认的布局管理器 BorderLayout...

    尝试使用类似...的东西

    FlowLayout f = new FlowLayout();
    setLayout(f);
    this.setTitle("this is a tittle");
    
    JButton button = new JButton();
    button.setText("Button");
    this.add(button);
    
    this.pack();
    this.setVisible(true);  
    

    相反...

    仔细查看Laying Out Components Within a Container了解更多详情

    【讨论】:

    • 谢谢。实际上我刚刚查看了我的代码,似乎我忘了添加 setlayout 东西,所以现在它工作正常。再次感谢:)
    【解决方案3】:

    FlowLayout 将在需要时从左到右(或从右到左)排列组件。如果您希望明确设置每个 JButton 的大小,则应使用 setPreferredSize 而不是 setSizesetBounds,因为布局管理器在执行布局时通常会使用最小、首选和最大尺寸。

    【解决方案4】:
    button.setBounds(x, y, height, width);
    

    你可以给出小于 10 的高度和宽度! 您也可以使用 GridLayout 在一个带有 for 循环的按钮中使用较小的按钮

    【讨论】:

      猜你喜欢
      • 2020-09-29
      • 1970-01-01
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-11
      • 2013-08-14
      相关资源
      最近更新 更多