Can we combine GridLayout and BorderLayout in Java?

Java 8Object Oriented ProgrammingProgramming

Yes, we can do that with Java Swings as shown below. Here, we have a panel set with GridLayout and another panel with BorderLayout −

JPanel panelGrid = new JPanel(new GridLayout(10, 5, 10, 10));
panelGrid.add(new JCheckBox("Demo CheckBox1"));
panelGrid.add(new JCheckBox("Demo CheckBox2"));
panelGrid.add(btnAPanel);
panelGrid.add(btnBPanel);
panelGrid.add(btnCPanel);
panelGrid.add(btnDPanel);
JPanel panelBrdLayout = new JPanel(new BorderLayout());
panelBrdLayout.add(panelGrid, BorderLayout.NORTH);

The following is an example to combine GridLayout and BorderLayout −

package my;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingDemo {
   public static void main(String[] args) {
      JButton btnA = new JButton("Button1");
      JButton btnB = new JButton("Button2");
      JButton btnC = new JButton("Button3");
      JButton btnD = new JButton("Button4");
      btnA.setPreferredSize(new Dimension(150, 20));
      btnB.setPreferredSize(new Dimension(150, 20));
      btnC.setPreferredSize(new Dimension(150, 20));
      btnD.setPreferredSize(new Dimension(150, 20));
      JPanel btnAPanel = new JPanel();
      JPanel btnBPanel = new JPanel();
      JPanel btnCPanel = new JPanel();
      JPanel btnDPanel = new JPanel();
      btnAPanel.add(btnA);
      btnBPanel.add(btnB);
      btnCPanel.add(btnC);
      btnDPanel.add(btnD);
      JPanel panelGrid = new JPanel(new GridLayout(10, 5, 10, 10));
      panelGrid.add(new JCheckBox("Demo CheckBox1"));
      panelGrid.add(new JCheckBox("Demo CheckBox2"));
      panelGrid.add(btnAPanel);
      panelGrid.add(btnBPanel);
      panelGrid.add(btnCPanel);
      panelGrid.add(btnDPanel);
      JPanel panelBrdLayout = new JPanel(new BorderLayout());
      panelBrdLayout.add(panelGrid, BorderLayout.NORTH);
      panelBrdLayout.setPreferredSize(new Dimension(550, 300));
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.add(panelBrdLayout);
      frame.setSize(550, 300);
      frame.setVisible(true);
   }
}

Output


raja
Published on 31-May-2019 11:31:08
Advertisements