JLabel in GridLayout

浪尽此生 提交于 2020-01-04 03:00:34

问题


How to add JLabel out of the GridLayout? I have an 8x8 grid layout.

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

回答1:


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 an 8x8 grid, change sz to 8.
  • If the 'label' mentioned is like the label seen in the GUI, it might go in the outer BorderLayout where Flow Layout (itself a panel) or Label appear as well as either of two other vacant positions in the outermost gui panel.
  • Both info (FlowLayout) & content (GridLayout) panels can also accept more components as needed.
  • Simple examples of other nested layouts.
    1. PlayerGui (31 LOC)

    2. WestPanel (30 LOC) not a great example as it extends JPanel instead of simply keeping an instance, but short.

    3. AmortizationLayout (53 LOC) especially nice as an example as it outlines the parent & child layouts using a titled border.



来源:https://stackoverflow.com/questions/14537443/jlabel-in-gridlayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!