views:

209

answers:

3

I m trying to make an array of labels each label has a differented value which come out of a function. I dont know the exact no. of labels to be used i mean there could be any no of values to b printed Therefore, please help me do so

A: 

Are you kiddin ? Well, in case you're serious, first take a look at some of the Java APIs, like JLabel, JPanel, and some of the language elements.

Then you'll be able to do something like (I'm sure my code won't compile)

public static JPanel getLabels(int count) {
    JPanel panel = new JPanel(new FlowLayout());
    for(int i =0; i<count; i++) {
        panel.add(new JLabel(theFunctionThatCannotBeNamedHere(i)));
    }
    return panel;
}

Notice that theFunctionThatCannotBeNamedHere is the function you talked about.

Riduidel
A: 

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]);
        }
    }
}
smeg4brains
A: 

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

Peter Lang