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

房东的猫 提交于 2020-01-03 16:36:11

问题


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.


回答1:


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



回答2:


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:


(source: sun.com)




回答3:


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.




回答4:


You can actually make an array of any Swing Component, since every Swing Component is basically composite data type. Try this:

javax.swing.JTextField[] array = new javax.swing.JTextField[number_of_elements];


来源:https://stackoverflow.com/questions/2712414/how-to-create-an-array-of-jlabels-in-java-to-be-printed-to-a-jframe

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