簡體   English   中英

如何設置JButton的大小?

[英]How do I set the size of a JButton?

該按鈕占據了整個屏幕,我嘗試使用setSize()但這似乎沒有任何作用。 到目前為止,這是我的代碼:

JButton start = new JButton("PLAY");
start.setSize(new Dimension(100, 100));
myFrame.add(start);

默認情況下, JFrame具有BorderLayoutCENTER對齊。 這就是為什么單個組件需要全屏顯示的原因。 因此,向JFrame添加合適的布局管理器。

有關詳細信息,請閱讀如何使用各種布局管理器

您可以嘗試使用GridBagLayoutContainer設置其大小。

img 導入java.awt.GridBagConstraints; 導入java.awt.GridBagLayout; 導入java.awt.Insets; 導入javax.swing.JButton; 導入javax.swing.JFrame; 導入javax.swing.JPanel;

public class test extends JPanel{
    private static final long serialVersionUID = 1L;
    JButton b1, b2, b3, b4, b5;
    GridBagConstraints g = new GridBagConstraints();
    public test() {
        setLayout(new GridBagLayout());
        g.insets = new Insets(1, 1, 1, 1);
        b1 = new JButton("Button 1");
        g.gridx = 0;
        g.gridy = 6;
        g.gridwidth = 2;
        g.gridheight = 1;
        g.fill = GridBagConstraints.HORIZONTAL;
        g.fill = GridBagConstraints.VERTICAL;
        add(b1, g);
        b2 = new JButton("Button 2");
        g.gridx = 0;
        g.gridy = 0;
        g.gridwidth = 3;
        g.gridheight = 1;
        g.fill = GridBagConstraints.HORIZONTAL;
        g.fill = GridBagConstraints.VERTICAL;
        add(b2, g);
        b3 = new JButton("Button 3");
        g.gridx = 2;
        g.gridy = 2;
        g.gridwidth = 1;
        g.gridheight = 1;
        g.fill = GridBagConstraints.HORIZONTAL;
        g.fill = GridBagConstraints.VERTICAL;
        add(b3, g);
        b4 = new JButton("Button 4");
        g.gridx = 6;
        g.gridy = 0;
        g.gridheight = 3;
        g.gridwidth = 1;
        g.fill = GridBagConstraints.HORIZONTAL;
        g.fill = GridBagConstraints.VERTICAL;
        add(b4, g);
        b5 = new JButton("Button 5");
        g.gridx = 1;
        g.gridy = 3;
        g.gridheight = 1;
        g.gridwidth = 2;
        g.fill = GridBagConstraints.HORIZONTAL;
        g.fill = GridBagConstraints.VERTICAL;
        add(b5, g);
    }
    public static void main(String[] args) {
    test t = new test();
    JFrame frame = new JFrame("test");
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.setLocationRelativeTo(null);
    frame.add(t);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM