Java: An array of JLabel

gaby10 Posted messages 445 Registration date   Status Member Last intervention   -  
 LabelMan -
Bonjour,
I want to display a table of JLabels, and each JLabel contains an image, but this piece of code gives me an exception during execution:

import javax.swing.*; import java.awt.*; class Personne1{ public static void main(String[] args){ Fenetre Fen=new Fenetre(); Fen.show(); } } class Fenetre extends JFrame{ Fenetre(){ this.setTitle("hello"); this.setPreferredSize(new Dimension(400,300)); JLabel label=new JLabel(new ImageIcon("user.png")); JLabel[][] label2=new JLabel[1][1]; for (int i=0;i<2;i++){ label2[i][i].setIcon(new ImageIcon("user.png")); this.add(label2[i][i]); } this.add(label); } }

Does anyone have an idea?
Thank you
Configuration: Windows XP Firefox 2.0.0.20

1 answer

Anonymous user
 
Normal !!

You do: JLabel[][] label2=new JLabel[1][1];
so an array with only one value!

Then you do a for loop and iterate from 0 to 2 exclusive, so 0 and 1, resulting in two values!

And why a 2-dimensional array?

Try this:

 int taille = X; //X is the number of JLabel JLabel[] label2=new JLabel[taille]; for (int i=0; i<taille; i++){ label2[i].setIcon(new ImageIcon("user.png")); this.add(label2[i]); } 


--
If someone helps you, a thank you and a solved (small box to the right of your first message)!!
4
LabelMan
 
You need to remember to initialize the label of your label table!
0