Java 项目赢得';我不能展示图片,我不知道为什么
我看到了一些其他的问题和答案,我做了和他们一样的事情,但我不明白为什么我的程序不起作用。我已经对代码进行了测试,直到它应该显示图像为止,它工作正常。它甚至会将imageNumber字符串更改为图片的名称,但不会显示它。以下是我所拥有的:Java 项目赢得';我不能展示图片,我不知道为什么,java,jpanel,imageicon,swingx,Java,Jpanel,Imageicon,Swingx,我看到了一些其他的问题和答案,我做了和他们一样的事情,但我不明白为什么我的程序不起作用。我已经对代码进行了测试,直到它应该显示图像为止,它工作正常。它甚至会将imageNumber字符串更改为图片的名称,但不会显示它。以下是我所拥有的: import javax.swing.*; import java.awt.event.*; import java.util.Random; public class DiceRollGUI { private static JPanel
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");
}
}
}
}
我很确定你忘记实际加载图像了
image = new JLabel(new ImageIcon(imageNumber));
切换/案例陈述后。您永远不会更改
操作执行中标签的图标
方法image.setIcon(新图像图标(图像编号)
会更简单,问题更少……这样OP就不会在屏幕上出现几十个标签:p这也行,我只是很久没有使用JFrame了,没有意识到这是一个可用的方法:p在你的答案下面有一个编辑链接,可以修改它,以防你看到改进答案的方法。