如何设置JButton的大小?

时间:2014-05-24 16:08:15

标签: java swing jframe jbutton border-layout

按钮占据整个屏幕,我尝试使用setSize(),但似乎没有做任何事情。到目前为止,这是我的代码:

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

2 个答案:

答案 0 :(得分:2)

默认情况下,JFrameBorderLayout对齐CENTER。这就是为什么单个组件将全屏显示。因此,为JFrame添加合适的布局管理器。

有关详细信息,请访问How to Use Various Layout Managers

答案 1 :(得分:1)

您可以尝试使用GridBagLayout将其大小设置为Container

img     import java.awt.GridBagConstraints;     import java.awt.GridBagLayout;     import java.awt.Insets;     import javax.swing.JButton;     import javax.swing.JFrame;     import 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);
    }
}