ImageIcon 不可见

ImageIcon not visible

我正在尝试将 ImageIcon 放在 JLabel 上,但它没有出现在 JFrame 中。我找不到错误的代码,我的控制台也没有显示任何错误。

代码如下:

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();


}

如果您的图像在项目当前工作目录中,只需使用 private ImageIcon d2 = new ImageIcon("images/d2.png") 而不使用 ./
注意:在您的测试代码中,您假设 getRandom 始终为 returns 零,只是想确保您对此有把握。

我认为如果图像位置正确,那么下一个问题就是随机数生成。 而不是

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

使用下面的代码生成随机数

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