javaswingfor-loopjlabelsettext

How can I change automatically a Label setter name in the program when it is running?


For example

JLabel label0 = new JLabel("");
JLabel label1 = new JLabel("");
JLabel label2 = new JLabel("");
JLabel label3 = new JLabel("");
JLabel label4 = new JLabel("");

for (int i = 0;i<5;i++)
{
    labeli.setText(i);
    
}

In this code, the for automatically change the label texts, first the label0 and after then the label1 etc.. Obviusly, this isn't working. My best solution was I do an if, and if i == 0 set label0 etc.. but maybe there is an easier solution which I don't know. (And if I make 100 elements, it is very long time to write down)


Solution

  • At the simplest of levels, you have a number of objects you want to maintain in an easy/accessible container. Assuming for a second that the list is of a predefined or, after it's initialisation, will never change size without needing to be be re-initialised, an array would be a good choice.

    See Arrays for more details.

    For example...

    import java.awt.EventQueue;
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    
    public class Test {
    
        public static void main(String[] args) {
            new Test();
        }
    
        public Test() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    JFrame frame = new JFrame();
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class TestPane extends JPanel {
    
            private JLabel[] labels = new JLabel[6];
    
            public TestPane() {
                setLayout(new GridLayout(0, 1));
                for (int index = 0; index < labels.length; index++) {
                    JLabel label = new JLabel(Integer.toString(index));
                    // Customise the label, as it' easy to type `label`
                    // then `labels[index]` ;)
                    add(label);
                    labels[index] = label;
                }
            }
    
        }
    
    }
    

    If, on the other hand, you need something which is more dynamic (can grow and shrink at runtime), then a List of some kind would be more practice, but since you don't seem to understand arrays, maybe you should stick with those first.