编程语言
首页 > 编程语言> > java-如何设置JButton的大小?

java-如何设置JButton的大小?

作者:互联网

我正在尝试设置JButton的大小,但是默认情况下会占用整个框架,它的高度很容易设置,但是我不能设置它的宽度&为什么它的行为我不知道.

我的代码:

    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);

有什么建议吗?

解决方法:

更改布局.尝试将按钮添加到另一个JPanel,然后将面板添加到框架.当组件放置在NORTH或SOUTH位置时,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);
            }
        });
    }

}

标签:swing,preferredsize,jbutton,layout-manager,java
来源: https://codeday.me/bug/20191030/1968718.html