I am practicing GUI in java. I am currently struggling with the placement of the elements. I want the JLabel to be in the center middle of the gui window and the button to be right below the JLabel. I wanna preface that I am a beginner in Java so I may have some lapses so I would appreciate some help/ tips as well!
I tried different layout manager(BoxLayout, GridLayout, BorderLayout, and FlowLayout) but neither of them worked. So far, FlowLayout was the closest but whenever I run the code the JLabel is placed on top and is seemingly cut off while the button is at the very bottom of the gui window.
here's a preview of my code:
import javax.swing.*;
import java.awt.*;
public class MyFrame extends JFrame {
public MyFrame(){
//panel for label
JPanel labelPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
//label for the intro
JLabel introLabel = new JLabel();
introLabel.setText("Welcome User");
introLabel.setForeground(new Color(129, 245, 71));
introLabel.setFont(new Font("Digital-7", Font.PLAIN, 24));
introLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
labelPanel.add(introLabel);
// panel for button
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
//JButton
JButton button = new JButton("click");
button.setFocusable(false);
buttonPanel.add(button);
//main content panel
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(labelPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
//set content of the pane
this.setContentPane(mainPanel);
//frame constructor
this.setSize(500, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("encrypt your message");
this.getContentPane().setBackground(new Color(0x151414)); // the gui bg is determined by the pane
this.setResizable(false);
//layout manager
this.setVisible(true);
}
}
I'd be inclined to do something like this.
BoxLayoutis your friend if you want things to be stacked. Also, you can use aGridBagLayoutin a 'shorthand` way to get things centred in a container: