1

In Netbeans: I have add 4 JLabel in one pane of JFrame:

enter image description here

I have create an array of JLabel:

private JLabel[] myLab = new JLabel[]{};

Please, I want to now, it's possible to make this JLabels (jLabel1, jLabel2, jLabel3, jLabel4) in one array, for call in program with MyLab[0], MyLab[ 1], MyLab[2], MyLab[3]?

1
  • Yes, probably better to use an ArrayList though. Can you show us what code you have attempted? Do you know what a for loop is? Commented Sep 23, 2018 at 16:37

1 Answer 1

2

Update (as markspace suggested) :

The correct syntax to create the array is,

private JLabel[] myLab2 = new JLabel[4];

because you need an array with a length of 4 to store 4 elements in the array. By using new JLabel[]{} you are creating an array with a length of 0.


You can't edit the generated codes in NetBeans. So assign the jLables to the array in the constructor after the initComponents(); statement.

myLab[0] = jLabel1;
myLab[1] = jLabel2;
myLab[2] = jLabel3;
myLab[3] = jLabel4;

Now refer jLable1 as myLab[0].

Sign up to request clarification or add additional context in comments.

1 Comment

Also the OP's example of creating an array is incorrect. private JLabel[] myLab2 = new JLabel[4]; is the correct syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.