Search code examples
javaswingline-breaks

Java - How to add line breaks in swings


I am adding a button to my minigame, but I do not know how to make a line break. I want one space in between the button and the text, and here's the code:

JPanel panel1 = new JPanel();
JLabel label1 = new JLabel("Welcome to the Wall Game!");
JLabel label2 = new JLabel("Click the button to read the instructions!");
JLabel space = new JLabel("");
JButton button1 = new JButton("Start");
button1.setText("Start!");

label1.setFont(font1); 
panel1.add(label1); //adds in all the labels to panels
panel1.add(label2);
panel1.add(space);
panel1.add(button1);
this.add(panel1); //adds the panel

What it shows in the Welcome message in a separate line, but for some reason the button is beside label2 Does someone know how?

By the way, you need import javax.swing.*; at the start if you didn't already know. Thanks to anyone who knows.


Solution

  • JPanel uses a FlowLayout by default, which obviously isn't meeting your needs. You could use a GridBagLayout instead.

    Have a look at Laying Out Components Within a Container and How to Use GridBagLayout for more details

    Something like...

    Welcome

    JPanel panel1 = new JPanel();
    JLabel label1 = new JLabel("Welcome to the Wall Game!");
    JLabel label2 = new JLabel("Click the button to read the instructions!");
    JButton button1 = new JButton("Start");
    button1.setText("Start!");
    
    Font font1 = label1.getFont().deriveFont(Font.BOLD, 24f);
    label1.setFont(font1);
    
    panel1.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    panel1.add(label1, gbc); //adds in all the labels to panels
    panel1.add(label2, gbc);
    gbc.insets = new Insets(30, 0, 0, 0);
    panel1.add(button1, gbc);
    

    as an example