【问题标题】:ImageIcon not visibleImageIcon 不可见
【发布时间】:2016-10-08 18:49:34
【问题描述】:

我正在尝试将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();


}

【问题讨论】:

  • 你在哪里添加了图片图标?
  • 这里:私有 ImageIcon c2 = new ImageIcon("./images/c2.jpg");在这里:card.setIcon(c2);
  • 尝试重新验证您的面板 (panel.revalidate())
  • 空布局所以重新验证什么都不做
  • @E.Reu 图像部分仅在 actionperform 发生时才有效。只需为您的 jlable 设置背景颜色,看看它是否可见? card = new JLabel(); card.setOpaque(true); card.setBackground(Color.yellow);

标签: java image swing awt imageicon


【解决方案1】:

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

【讨论】:

  • 我不敢相信。错误的部分确实是 getRandom 方法 O.o 谢谢你的注意 :)
【解决方案2】:

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

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

使用以下代码生成随机数

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

【讨论】:

    猜你喜欢
    • 2015-07-20
    • 1970-01-01
    • 2014-04-04
    • 2011-09-04
    • 2015-04-18
    • 2017-09-26
    • 2015-07-25
    • 2012-06-08
    • 2017-02-26
    相关资源
    最近更新 更多