简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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