JLabel in GridLayout

How to add JLabel

from GridLayout

? I have an 8x8 grid.

Container content = getContentPane();
content.setLayout(new GridLayout(8, 8,2,2));
for (int f = 0; f < btnArr.length; f++){
    for (int s = 0; s < btnArr.length; s++){
        btnArr[f][s] = new JButton();
        btnArr[f][s].addActionListener(this);
        content.add(btnArr[f][s]);
        btnArr[f][s].setBackground(randomColor());
    }
}

      

+3


source to share


1 answer


SimpleNestedLayout

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

class SimpleNestedLayout {

    public static void main(String[] args) {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                JPanel gui = new JPanel(new BorderLayout(5,5));

                int sz = 4;
                Container content = new JPanel(new GridLayout(sz, 0, 2, 2));
                for (int f=0; f<sz*sz; f++) {
                    content.add(new JButton());
                }
                gui.add(content, BorderLayout.CENTER);

                Container info = new JPanel(
                        new FlowLayout(FlowLayout.CENTER, 50, 5));
                info.add(new JLabel("Flow"));
                info.add(new JLabel("Layout"));
                gui.add(info, BorderLayout.PAGE_START);

                gui.add(new JLabel("Label"), BorderLayout.LINE_END);

                JOptionPane.showMessageDialog(null, gui);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

      



Notes

  • For the 8x8 grid, change sz

    to 8.
  • If said "label" is similar to a shortcut seen in the GUI, it can be in the outer BorderLayout

    where Flow

    Layout

    (the panel itself) appears or Label

    , as well as one of two other free positions in the outermost panel gui

    .
  • Both panels info

    ( FlowLayout

    ) and content

    ( GridLayout

    ) can also accept more components as needed.
  • Simple examples of other nested layouts.
+9


source







All Articles