我正在尝试设置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);
有什么建议吗?
答案 0 :(得分:6)
更改布局。尝试将按钮添加到另一个JPanel
,然后将面板添加到框架中。当组件放置在BorderLayout
或NORTH
位置时,SOUTH
会在面板的可用宽度上拉伸按钮
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);
}
});
}
}
答案 1 :(得分:-2)
getContentPane().setLayout(null);
//setBounds(x,y,width,height)
btnNewButton.setBounds(10,10,250,100);
getContentPane().add(btnNewButton);