Search code examples
javaswingjlabel

Auto create JLabels should be under themselves


I have a code that automatically create jlabels .

I want that each label should be at a row, Not beside!

I use this code:

            lbl = new JLabel[rows];
        for (int i = 0; i < rows; i++) {
            lbl[i] = new JLabel(arrayResultRow[i].toString()+ "\n" );
        }

But \n does not work!


Solution

  • Google and study the Java Swing layout manager tutorial and start reading.

    Likely you're adding the JLabels to a JPanel which uses FlowLayout by default, and you need to change the layout of the container to GridLayout or BoxLayout.

    Edit: here's the link: Laying out Components.

    i.e.,

    // add JLabels to a JPanel that uses GridLayout set to have
    // 1 column and "rows" number of rows.
    JPanel labelHolder = new JPanel(new GridLayout(rows, 1);
    lbl = new JLabel[rows];
    for (int i = 0; i < rows; i++) {
      lbl[i] = new JLabel(arrayResultRow[i].toString());
      labelHolder.add(lbl[i]);
    }