How to display labels in the form of a 4 column table with GridLayout in Java?


We will displays labels in a label with 5 rows and 4 columns using GridLayout −

JPanel panel = new JPanel(new GridLayout(5, 4, 10, 10));

Use a for loop and loop through 1 to 20 to display 20 labels −

for (int i = 1; i <= 20; i++) {
   panel.add(new JLabel("Displaying label "+String.valueOf(i)));
}

The following is an example to display labels in the form of a 4 column table −

Example

package my;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      JPanel panel = new JPanel(new GridLayout(5, 4, 10, 10));
      for (int i = 1; i <= 20; i++) {
         panel.add(new JLabel("Displaying label "+String.valueOf(i)));
      }
      frame.add(panel);
      frame.setSize(550, 300);
      frame.setVisible(true);
   }
}

Output

Updated on: 30-Jul-2019

645 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements