So I have this program I’m working on that displays 3 random cards in the frame with labels. So far I have it to assign a deck of cards to an array of ImageIcons and then shuffle them. My question is, How do I go about assigning them to JLabels now. Forgive me for the stupid question, as I know it is something simple but I’m very new to using GUI and it frightens me lol
here’s my code so far:
package assignment2;
import javax.swing.*;
import java.awt.*;
public class Assignment2 extends JFrame{
public Assignment2(){
setLayout(new GridLayout(3,1,5,5));
add(new JLabel()); ///display one random card
add(new JLabel()); ////display another random card
add(new JLabel()); ////display another random card
}
public static void main(String[] args) {
Assignment2 frame = new Assignment2();
frame.setTitle("MAIN TO THE FRAME");
frame.setSize(600,300);
frame.setResizable(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final int FINAL_CARDS_NUMBER = 54;
ImageIcon deckOfCards [] = new ImageIcon [FINAL_CARDS_NUMBER];
for(int i = 0; i <FINAL_CARDS_NUMBER; i++){
deckOfCards[i] = new ImageIcon("C:/card/" + (i + 1) + ".png");
}
for (int i = 0; i < FINAL_CARDS_NUMBER; i++) {
int r = i + (int) (Math.random() * (FINAL_CARDS_NUMBER-i));
ImageIcon t = deckOfCards[r];
deckOfCards[r] = deckOfCards[i];
deckOfCards[i] = t;
}
}
}
First, remove the 3 lines where you add the labels:
Then, in the place where you are getting the
ImageIcon, do this:However, I suggest you don’t set the layout and add components directly to your
JFrame. You would better create a newJPaneland add that to the content pane of yourJFrame:Then, when you add the labels, add them to the panel.
Now that you updated the question, I am updating the answer below.
First, declare 3
JLabel, instantiate them and add them to the panel as explained above.Then, after you read the
ImageIconfor each, you can set theJLabelimage this way: