简体   繁体   中英

Loop using jLabels in swing

how can a make a loop using this labels instead of creating 40 lines of code "repeating" them

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")));

You write a loop. So set i to 0 ( int i=0 ), while it is less than 40 ( i<40 ), continue to loop, every loop add 1 to i ( i++ )

 for (int i=0; i<40; i++)
 {
 }

Then you insert the code to be looped, using the changing i to index whatever it is you want to index

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

In your case, you will need to create a bunch of labels though as

 JLabel[] jLabels = new JLabel[40];

Then you can index each label inside your loop

//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); 

But you will need to have a simple loop (before the one above ... or within it) in order to fill the jLabels array with new JLabel() objects. I've given you all the tools you need to do that.

The way that i like to do it, is to create a Vector object that holds JLabels, like below.

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

After that you can go on and create a method called createLabel() that take in a name, text, width, height and other options you wish to set. For example you may want to set the location of the label or even add a actionListener to it. Below is what i like to take in and set.

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.
}

And to call the method.

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

If you need to get the label you will need to add a getter for the vector and to get the label put.

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

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM