简体   繁体   English

程序不会显示图片,我也不知道为什么

[英]Program won't display pictures and I have no idea why

I've seen some other questions and answers and I've done the same thing as them, but I can't figure out why my program won't work. 我看过其他一些问题和答案,并且做过同样的事情,但是我不知道为什么我的程序无法正常工作。 I've tested the code and it works fine up until when it should display the image. 我已经测试了代码,并且可以正常工作,直到它应该显示图像为止。 It even changes the string of imageNumber to the name of the picture, but wont display it. 它甚至将imageNumber的字符串更改为图片的名称,但不会显示它。 Here is what I have: 这是我所拥有的:

import javax.swing.*;
import java.awt.event.*;
import java.util.Random;

public class DiceRollGUI {

        private static JPanel panel = new JPanel();
        private static String imageNumber = "No Set Image";
        private static JLabel image = new JLabel(new ImageIcon(imageNumber));
        private static JButton rollDie = new JButton("Roll die");

    public static void main(String[] args) {
        JFrame frame = new JFrame("Dice Roll GUI");
        JLabel labelOne = new JLabel("Press 'Roll' to roll the 6 sided die.");

        rollDie.setActionCommand("Roll");
        rollDie.addActionListener(new Button());

        frame.setVisible(true);
        frame.setSize(600, 700);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(panel);

        panel.add(labelOne);
        panel.add(rollDie);
    }

    public static class Button implements ActionListener {

        public void actionPerformed(ActionEvent event) {

            String command = event.getActionCommand();
            Random random = new Random();
            int randomNum = random.nextInt(6) + 1;

            if (command.equals("Roll")) {
                switch (randomNum) {
                    case 1:
                        imageNumber = ("dice1.png");
                        break;
                    case 2:
                        imageNumber = ("dice2.png");
                        break;
                    case 3:
                        imageNumber = ("dice3.png");
                        break;  
                    case 4:
                        imageNumber = ("dice4.png");
                        break;
                    case 5:
                        imageNumber = ("dice5.png");
                        break;
                    default:
                        imageNumber = ("dice6.png");
                        break;
                }
                panel.add(image);
                rollDie.setText("Roll Again");
                imageNumber = ("No Set Image");
            }
        }
    }
}

I'm pretty sure you forgot to actually load the image 我敢肯定你忘了实际加载图像

image = new JLabel(new ImageIcon(imageNumber));

after the switch/case statement. 在switch / case语句之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM