循环使用jLabels

时间:2014-09-12 10:29:27

标签: java swing loops jlabel

如何使用此标签制作循环,而不是创建40行代码“重复”它们

jLabel1.setIcon(new ImageIcon(getClass().getResource("/cards/"+cards.get(1)+".png"))); 
jLabel2.setIcon(new ImageIcon(getClass().getResource("/cards/"+cards.get(1)+".png"))); 
jLabel3.setIcon(new ImageIcon(getClass().getResource("/cards/"+cards.get(2)+".png"))); 
jLabel4.setIcon(new ImageIcon(getClass().getResource("/cards/"+cards.get(3)+".png")));

2 个答案:

答案 0 :(得分:5)

你写了一个循环。因此,将i设置为0(int i=0),当它小于40(i<40)时,继续循环,每个循环将{1}添加到i({{1} })

i++

然后插入要循环的代码,使用更改 for (int i=0; i<40; i++) { } 来索引您要索引的内容

i

在您的情况下,您需要创建一堆标签,但

 for (int i=0; i<40; i++)
 {
    //do something with i - which is increased by one every loop through
 }

然后你可以索引循环中的每个标签

 JLabel[] jLabels = new JLabel[40];

但是你需要有一个简单的循环(在上面的那个之前......或者在它之内),以便用//Notice there are two uses of the i variable here String imageLocation = "/cards/" + cards.get(i) + ".png"; ImageIcon icon = new ImageIcon(getClass().getResource(imageLocation)); jLabels[i].setIcon(icon); 对象填充jLabels数组。我已经为您提供了所需的所有工具。

答案 1 :(得分:0)

我喜欢这样做的方法是创建一个包含JLabel的Vector对象,如下所示。

private Vector<JLabel> vecLabels = new Vector<JLabel>();

之后,您可以继续创建一个名为createLabel()的方法,该方法包含您希望设置的名称,文本,宽度,高度和其他选项。例如,您可能想要设置标签的位置,甚至可以向其添加actionListener。以下是我想接受和设定的内容。

public void createLabel(String text, String name, Dimension size, Point location) {
        JLabel label = new JLabel(text); // Creates the JLabel
        label.setName(name); // Sets the name
        label.setSize(size); // Sets the size
        label.setLocation(location); // Sets the location
        vecLabel.add(label); // Adds the JLabel to the vecLabels. ()
        add(label); // Adds the label to the JFrame.
}

并调用该方法。

createLabel("Name:", "lblName", new Dimension(100, 25), new Point(xPos, yPos));

如果你需要获得标签,你需要为矢量添加一个getter并获得标签。

 public JLabel getLabel(int index) {
        return vecLabel.get(index);
    }
    private JLabel lblLabel = getLabel(Index);

希望这有帮助。