如何在 Java 中创建要打印到 JFrame 的 JLabel 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2712414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:58:14  来源:igfitidea点击:

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

javaarraysswingjframejlabel

提问by vishesh

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.

我正在尝试制作一系列标签。每个标签都有一个不同的值,这些值来自一个函数。我不知道要使用的确切标签数量。我的意思是可以打印任意数量的值。请帮我做这件事。

回答by Riduidel

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.

你在开玩笑吗?好吧,如果您是认真的,首先看看一些 Java API,比如 JLabel、JPanel 和一些语言元素。

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 theFunctionThatCannotBeNamedHereis the function you talked about.

请注意,这theFunctionThatCannotBeNamedHere就是您所说的功能。

回答by fasseg

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)

很简单,只需一个方法返回一个数组或一些 JLabel 集合,并将它们全部添加到您的 JComponent(例如 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]);
        }
    }
}

回答by Peter Lang

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

如果可能,不要使用单独的JLabels,而是使用 a JList,它会在必要时处理布局和滚动。

Java-Tutorial - How to us a List:

Java 教程 - 如何使用列表

alt text
(source: sun.com)

替代文字
(来源:sun.com

回答by Vatsal Srivastava

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

您实际上可以创建任何 Swing 组件的数组,因为每个 Swing 组件基本上都是复合数据类型。尝试这个:

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