Recently, I have started doing UI development in Java; I used to do UI development in WPF.
Some things about Java way of doing things are confusing.
What I am trying to achieve is to set minimum size of a button.
Here is the simplified code:
public class MainGameView extends JPanel {
public MainGameView(DefaultController controller) {
this.controller = controller;
CreateUI();
}
private void CreateUI() {
MenuPanel = new javax.swing.JPanel();
StartGameBtn = new JButton("Start Game");
// Creating menu
MenuPanel.setLayout(new BoxLayout(MenuPanel, BoxLayout.Y_AXIS));
MenuPanel.setPreferredSize(new Dimension(200, 200));
StartGameBtn.setAlignmentX(Component.LEFT_ALIGNMENT);
StartGameBtn.setMinimumSize(new Dimension(200, 30));
MenuPanel.add(StartGameBtn);
}
}
So to my understanding, if the container gets allocated 200 pixels as its width, it should accordingly allocate 200 pixels of width to the button. However button stays the same size. Am I missing something here?
The BoxLayout will not stretch a component horizontally, it will allow it to remain at it’s preferred width. You should use a layout manager that does stretch horizontally. For example, based on what it looks like you are trying to do, you could use the BorderLayout:
This puts the button at the top, maintains its natural preferred height, and stretches it horizontally to fit the MenuPanel’s width even if it is resized. You might also look at the GridLayout (configured with 1 column) which I believe will let you add multiple components in a vertical column and all the components will stretch to fit the entire width of the MainPanel.