put 2 labels into the middle of a jframe border layout

Viewed 565

My java code produces a label in the middle with a button on the top and bottom. I want the code below to produce something that looks like this.

enter image description here

I just don't know how to add 2 labels to the center with this code f.add(b2,BorderLayout.CENTER); . Because it seems like only one item can be in the center. My code wants both labels to be symmetrical that are in the center.

import java.awt.*;
import java.io.IOException;
import javax.swing.*;

public class may2 {
    Frame f;  
    JLabel b2=new JLabel("");;  

    may2() throws IOException{ 
        f=new JFrame();  
        JButton b1 = new JButton("First");
        JButton b3 = new JButton("Second");
        f.add(b1,BorderLayout.NORTH); 
        f.add(b2,BorderLayout.CENTER);  
        f.add(b3,BorderLayout.SOUTH); 
        f.setSize(400,500);  
        f.setVisible(true);  
    }

    public static void main(String[] args) throws IOException {  
        new may2();  
    }  

}
1 Answers

The key: nest JPanels, each using its own layout manager.

Create a JPanel and give it a new GridLayout(1, 0) for 1 row, variable number of columns. Add your JLabels to this JPanel and then add this JPanel into the BorderLayout.CENTER position of the main container, the one using BorderLayout.

e.g.,

import java.awt.*;
import java.io.IOException;
import javax.swing.*;

public class May2b {
    Frame f;  
    JLabel label1 = new JLabel("Label 1");  
    JLabel label2 = new JLabel("Label 2");  

    May2b() throws IOException{ 
        JPanel centerPanel = new JPanel(new GridLayout(1, 0));
        centerPanel.add(label1);
        centerPanel.add(label2);

        f = new JFrame();  
        JButton b1 = new JButton("First");
        JButton b3 = new JButton("Second");
        f.add(b1,BorderLayout.NORTH); 
        f.add(centerPanel, BorderLayout.CENTER);  
        f.add(b3,BorderLayout.SOUTH); 

        f.pack();
        // f.setSize(400,500);  

        f.setVisible(true);  
    }

    public static void main(String[] args) throws IOException {  
        new May2b();  
    }  
}

Also:

  • Class names should begin with an upper-case letter to follow Java conventions. This will make it easier for others to read your code.
  • Avoid setting a JPanel's size and instead call pack() on it after adding all components and before setting it visible. This will tell the layout managers and the components to re-size components as per their preferred sizes.
Related