Search code examples
javaswingjframejlabel

Array of JLabel in swing


I have recently started using swing in java and I want to add to my JFrame two-dimensional array of JLabels, problem is, that I want to put on the same JFrame antoher things like JButtons etc. And my problem is, that I don't know how to add this array of JLabels.


Solution

  • You could take a look at the GridLayout.

    With this layout you could create a two dimensional layout, in which you could add the JLabels.

    Something like:

    JPanel container = new JPanel();
    GridLayout experimentLayout = new GridLayout(0,2);
    
    container.setLayout(experimentLayout);
    
    container.add(new JButton("Label 1,1"));
    container.add(new JButton("Label 1,2"));
    container.add(new JButton("Label 2,1"));
    container.add(new JButton("Label 2,2"));
    

    This would return a grid like:

    +-----------+-----------+
    | Label 1,1 | Label 1,2 |
    +-----------+-----------+
    | Label 2,1 | Label 2,2 |
    +-----------+-----------+