4

我正在尝试设置 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);

请问有什么建议吗?

4

2 回答 2

7

改变布局。尝试将按钮添加到另一个按钮,JPanel然后将面板添加到框架中。 BorderLayout当组件放置在NORTHorSOUTH位置时,将在面板的可用宽度上拉伸按钮

在此处输入图像描述

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

}
于 2013-08-13T05:47:18.740 回答
-2
  getContentPane().setLayout(null);
  //setBounds(x,y,width,height)
  btnNewButton.setBounds(10,10,250,100);
  getContentPane().add(btnNewButton);
于 2013-08-13T05:52:17.920 回答