20

How do we show the gridline in GridLayout? in Java?

JPanel panel = new JPanel(new GridLayout(10,10));
panel.setBorder(BorderFactory.createEmptyBorder(2,2,2,2));

for (int i =0; i<(10*10); i++){
   panel.add(new JLabel("Label"));
}

6 Answers 6

19

I would try to do it by adding borders to the components as they are added. The simple way to do it is just using BorderFactory.createLineBorder(), like this:

JPanel panel = new JPanel(new GridLayout(10,10));
panel.setBorder(BorderFactory.createEmptyBorder(2,2,2,2));

for (int i =0; i<(10*10); i++){
    final JLabel label = new JLabel("Label");
    label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    panel.add(label);
}

However, that will give you thicker borders between the cells than at the edges of the panel, because the outer edges will only have a one-pixel thick border and the inside edges will have two one-pixel thick borders together. To work around that, you can use BorderFactory.createMatteBorder() to only draw one-pixel-wide borders everywhere:

final int borderWidth = 1;
final int rows = 10;
final int cols = 10;
JPanel panel = new JPanel(new GridLayout(rows, cols));
panel.setBorder(BorderFactory.createEmptyBorder(2,2,2,2));

for (int row = 0; row < rows; row++) {
    for (int col = 0; col < cols; col++) {
        final JLabel label = new JLabel("Label");
        if (row == 0) {
            if (col == 0) {
                // Top left corner, draw all sides
                label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            }
            else {
                // Top edge, draw all sides except left edge
                label.setBorder(BorderFactory.createMatteBorder(borderWidth, 
                                                                0, 
                                                                borderWidth, 
                                                                borderWidth, 
                                                                Color.BLACK));
            }
        }
        else {
            if (col == 0) {
                // Left-hand edge, draw all sides except top
                label.setBorder(BorderFactory.createMatteBorder(0, 
                                                                borderWidth, 
                                                                borderWidth, 
                                                                borderWidth, 
                                                                Color.BLACK));
            }
            else {
                // Neither top edge nor left edge, skip both top and left lines
                label.setBorder(BorderFactory.createMatteBorder(0, 
                                                                0, 
                                                                borderWidth, 
                                                                borderWidth, 
                                                                Color.BLACK));
            }
        }
        panel.add(label);
    }
}

This should give you borders of width borderWidth everywhere, both between cells and along the outside edges.

3
  • 2
    You're welcome. Good example of a question, by the way - I was able to cut-and-paste your code directly into Eclipse and run it, which made it very easy to test my solution. Mar 15, 2010 at 0:19
  • tried to get this to pop up, but when I ran it the JFrame was empty, nothing there
    – Ungeheuer
    Jun 7, 2015 at 21:10
  • neither blocks of code did. did I forget to do something?
    – Ungeheuer
    Jun 7, 2015 at 21:12
9

There is an easier work around to the thick borders problem mentioned by Joe Carnahan: GridLayout(10,10, -1, -1) sets the vertical gaps and the horizontal gaps between components to -1. So the full code is:

JPanel panel = new JPanel(new GridLayout(10,10, -1, -1));
panel.setBorder(BorderFactory.createEmptyBorder(2,2,2,2));

for (int i =0; i<(10*10); i++){
    final JLabel label = new JLabel("Label");
    label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    panel.add(label);
}
9

I found a very simple solution:

    final GridBagLayout layout = new GridBagLayout();
    JPanel content = new JPanel(layout)
    {

        @Override
        public void paint(Graphics g)
        {
            super.paint(g);
            int[][] dims = layout.getLayoutDimensions();
            g.setColor(Color.BLUE);
            int x = 0;
            for (int add : dims[0])
            {
                x += add;
                g.drawLine(x, 0, x, getHeight());
            }
            int y = 0;
            for (int add : dims[1])
            {
                y += add;
                g.drawLine(0, y, getWidth(), y);
            }
        }

    };

EDIT: For this solution i simply override the paint() method of the JPanel and paint the grid as defined by GridBagLayout.getLayoutDimensions() manually on top of the JPanel's own image.

5
  • 1
    and what does this do? there should always be an explanation of how the answer works along with the answer you provide. Dropping in only code is not acceptable
    – Ungeheuer
    Jun 7, 2015 at 20:56
  • 2
    I added an explanation. Jun 11, 2015 at 16:32
  • 3
    @Ungeheuer In this instance dropping in code was perfectly acceptable. Going around saying everything is "not acceptable" is not acceptable. Jan 21, 2022 at 14:56
  • 1
    While this is exactly what I was looking for, I've got to point out that the OP asked for GridLayout instead of GridBagLayout. Feb 11, 2022 at 11:59
  • Oh, you are right. Maybe you can adjust the code to work with GridLayout and post another answer for it? Mar 17, 2022 at 14:21
0

I would be tempted to use JLayeredPane to place a non-opaque component over the top that draws lines based on the grid.

1
  • could you add some code to this answer to show how that would work?
    – Ungeheuer
    Jun 7, 2015 at 20:57
0

Or just set the background color of the panel to be your border color and the gridlines will appear like magic:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

public class GridLayoutLines extends JFrame
{
    public GridLayoutLines()
    {
        JPanel grid = new JPanel( new GridLayout(10, 10, 2, 2) );
        grid.setBackground( Color.BLACK );
        grid.setBorder( new MatteBorder(2, 2, 2, 2, Color.BLACK) );

        for (int i = 0; i < 100; i++)
        {
            JLabel label = new JLabel();
            label.setText(" label" + i);
            label.setOpaque( true );
            grid.add( label );
        }

        add( grid );
    }

    public static void main(String[] args)
    {
        GridLayoutLines frame = new GridLayoutLines();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}
0
//http://www.geekssay.com/how-to-make-grid-layout-using-swing/

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

class GridExample {

 private JFrame f;

 private JButton b1, b2, b3, b4, b5, b6;

 
public GridExample() {

 f = new JFrame("Grid Example");

 b1 = new JButton("Button 1");

 b2 = new JButton("Button 2");

 b3 = new JButton("Button 3");

 b4 = new JButton("Button 4");
 b5 = new JButton("Button 5");
 b6 = new JButton("Button 6");
 }
 
public void launchFrame() {
 f.setLayout (new GridLayout(3,2));
 
f.add(b1);

 f.add(b2);

 f.add(b3);
 f.add(b4);

 f.add(b5);
 f.add(b6);

 
f.pack();
 f.setVisible(true);

 }
 
public static void main(String args[]) {

 GridExample grid = new GridExample();
 grid.launchFrame();
 }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.