简体   繁体   English

如何设置JButton的大小?

[英]How to set size of JButton?

i am trying to set size of JButton, but by default it take whole frame, it's height easily set but i can't set it's width & why its behaving like that i don't know. 我试图设置JButton的大小,但默认情况下它需要整个框架,它的高度很容易设置,但我不能设置它的宽度和为什么它的行为像我不知道。

my code : 我的代码:

    JButton btnNewButton = new JButton("");
    btnNewButton.setPreferredSize(new Dimension(32,0));
    ImageIcon icon = new    ImageIcon(this.getClass().getResource("/images/images_Left.png"));
    btnNewButton.setIcon(icon);
    boxTlacitek.add(btnNewButton);
    getContentPane().add(btnNewButton, BorderLayout.NORTH);

any suggestion please ? 有什么建议吗?

Change the layout. 更改布局。 Try adding the button to another JPanel then add the panel the frame. 尝试将按钮添加到另一个JPanel然后添加面板框架。 BorderLayout will stretch the button across the available width of the panel when the component is placed in the NORTH or SOUTH position 当组件放置在NORTHSOUTH位置时, BorderLayout将在面板的可用宽度上拉伸按钮

在此输入图像描述

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestBorderLayout {

    public static void main(String[] args) {
        new TestBorderLayout();
    }

    public TestBorderLayout() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JButton fat = new JButton("Fat");
                JButton skinny = new JButton("Skinny");

                JPanel buttonPane = new JPanel();
                buttonPane.add(skinny);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(fat, BorderLayout.NORTH);
                frame.add(buttonPane, BorderLayout.SOUTH);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}
  getContentPane().setLayout(null);
  //setBounds(x,y,width,height)
  btnNewButton.setBounds(10,10,250,100);
  getContentPane().add(btnNewButton);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM