Подтвердить что ты не робот

Как показать сетку в GridLayout?

Как показать сетку в GridLayout? в 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"));
}
4b9b3361

Ответ 1

Я попытался бы сделать это, добавив границы к компонентам по мере их добавления. Простой способ сделать это - просто использовать BorderFactory.createLineBorder(), например:

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);
}

Тем не менее, это даст вам более плотные границы между ячейками, чем по краям панели, потому что внешние края будут иметь только однопиксельную границу, а внутренние края будут иметь две однопиксельные границы. Чтобы обойти это, вы можете использовать BorderFactory.createMatteBorder() только для того, чтобы везде рисовать ширины всего на один пиксель:

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);
    }
}

Это должно давать границы ширины borderWidth везде, как между ячейками, так и по внешним краям.

Ответ 2

Существует более легкая работа над проблемой плотных границ, упомянутой Джо Карнахеном: GridLayout(10,10, -1, -1) устанавливает вертикальные зазоры и горизонтальные промежутки между компонентами -1. Таким образом, полный код:

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);
}

Ответ 3

Я нашел очень простое решение:

    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: для этого решения я просто переопределяю метод paint() JPanel и крашу сетку, как определено GridBagLayout.getLayoutDimensions() вручную поверх собственного изображения JPanel.

Ответ 4

У меня возникло бы желание использовать JLayeredPane для размещения непрозрачного компонента сверху, который рисует линии на основе сетки.

Ответ 5

Или просто установите цвет фона панели как цвет границы, а сетки появятся как 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);
    }
}

Ответ 6

//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();
 }
}