I am creating a higher or lower card game, and currently, it generates a random number from 1
to 13
as just a simple string label (1,2,3,4
etc), depending on what number gets pulled.
Instead of this, I would like to show a graphic of the card corresponding to the number.
Asked
Active
Viewed 89 times
0

Davide Spataro
- 7,319
- 1
- 24
- 36

C.Roberts
- 65
- 1
- 1
- 6
-
https://stackoverflow.com/questions/3775373/java-how-to-add-image-to-jlabel – jsheeran Jul 31 '17 at 10:22
2 Answers
0
public int getRandomNumber(){
Random r = new Random();
int nr = r.nextInt(13);
return nr;
}
...
JLabel label = new JLabel(getRandomNumber(), JLabel.CENTER);
To Update Label text you can use this method
public void updateLabel(int nr){
label.setText(nr+"");
//place this method inside your Jframe class extend from javax.swing.Jframe
}
If you want to put an image according to the number. Supose you have an array of 13 images(numbers)//Image images[13]; then you can use this
public void setIcon(int nr){
ImageIcon icon = new ImageIcon(images[nr]);
label.setIcon(icon);
}

Indrit Kello
- 1,293
- 8
- 19
0
I think that what you are looking for is adding an Icon
to a JLabel
.
You can do that using the setIcon
method which accept any implementation of Icon
, as for instance ImageIcon
.
Something like the following should work:
ImageIcon imgIcon = new ImageIcon(URL_OF_THE_PIC));
jLabel.setIcon(imgIcon);
and whenever a new card gets picked you can change text and Icon accordingly.

Davide Spataro
- 7,319
- 1
- 24
- 36