How to set size of JButton?
java, jbutton, layout-manager, preferredsize, swing
Solution
Change the layout. Try adding the button to another `JPanel` then add the panel the frame. `BorderLayout` will stretch the button across the available width of the panel when the component is placed in the `NORTH` or `SOUTH` position
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);
}
});
}
}
Problem
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. 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 ?