改变布局。尝试将按钮添加到另一个按钮,JPanel
然后将面板添加到框架中。 BorderLayout
当组件放置在NORTH
orSOUTH
位置时,将在面板的可用宽度上拉伸按钮
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);
}
});
}
}