Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array of JLabels in Java to be printed to a JFrame

I m trying to make an array of labels. Each label has a differented value which come out of a function. I don't know the exact number of labels to be used. I mean there could be any number of values to be printed. Please help me do this.

like image 962
vishesh Avatar asked Jan 23 '23 04:01

vishesh


2 Answers

easy just have one method return an array or some collection of JLabels and add all of them to your JComponent (e.g. a JPanel)

class MyPanel extends JPanel{

    public MyPanel(){
        super();
        showGUI();
    }

    private JLabel[] createLabels(){
        JLabel[] labels=new JLabel[10]
        for (int i=0;i<10;i++){
            labels[i]=new JLabel("message" + i);
        }
        return labels;
    }

    private void showGUI(){
        JLabel[] labels=createLabels();
        for (int i=0;i<labels.length();i++){
            this.add(labels[i]);
        }
    }
}
like image 147
fasseg Avatar answered Jan 29 '23 14:01

fasseg


If possible, don't use separate JLabels, but a JList, which will take care of layout and scrolling if necessary.

Java-Tutorial - How to us a List:

alt text
(source: sun.com)

like image 42
Peter Lang Avatar answered Jan 29 '23 14:01

Peter Lang