user5647258
user5647258

Reputation:

ImageIcon not visible

I'm trying to put a ImageIcon on a JLabel but it doesn't appear in the JFrame. I can't find the wrong code and my console doesn't show any errors.

Here's the code:

public class Gui extends JFrame implements ActionListener {

    private JLabel card;
    private JButton bBet;
    private ImageIcon c2 = new ImageIcon("./images/c2.jpg");
    private ImageIcon d2 = new ImageIcon("./images/d2.jpg");
    private ImageIcon h2 = new ImageIcon("./images/h2.jpg");
    private ImageIcon s2 = new ImageIcon("./images/s2.jpg");
    private JPanel panel;
    private int cardx1 = 250, cardy1 = 400;

    public Gui() {

        this.setTitle("Simple Blackjack");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(1200, 800);
        this.setLayout(null);

        panel = new JPanel();
        panel.setBounds(10, 10, 1200, 800);
        panel.setLayout(null);

        bBet = new JButton("Bet");
        bBet.setBounds(10, 70, 200, 35);
        bBet.addActionListener(this);
        panel.add(bBet);

        this.add(panel);
        this.setVisible(true);

}

public void actionPerformed(ActionEvent event) {

    if (event.getSource() == bBet) {
        random = getRandom();
        addLabel(cardx1, cardy1, random);
    }


}

public void addLabel(int x, int y, int random) {

    Random r = new Random(4);
    int which = r.nextInt();

    card = new JLabel();
    card.setBounds(x, y, 166, 230);

    switch (random) {
    case 0:
        if (which == 0){
            card.setIcon(c2);
        } else if (which == 1) {
            card.setIcon(d2);
        } else if (which == 2) {
            card.setIcon(h2);
        } else if (which == 3) {
            card.setIcon(s2);
        }
        break;
    }

    panel.add(card);
    panel.repaint();


}

Upvotes: 1

Views: 91

Answers (2)

Beniton Fernando
Beniton Fernando

Reputation: 1533

I think if the images are properly located then the next problem would be Random number generation. Instead of

    Random r = new Random(4);
    int which = r.nextInt();

Use the below code to generate the random numbers

ThreadLocalRandom.current().nextInt(0, 4);

Upvotes: 0

Jalal Kiswani
Jalal Kiswani

Reputation: 765

If your images in the project current working directory, just use private ImageIcon d2 = new ImageIcon("images/d2.png") without ./ enter image description here
Note: in your test code, you assume that the getRandom are always returns zero , just want to be sure that you sure about it.

Upvotes: 1

Related Questions