GUI图像显示 [英] GUI image display
问题描述
这是我为显示随机卡而制作的代码。随机卡选择工作正常,但图像不显示。
This is the code that I made for displaying random cards. The random card selection is working fine, but the images are not displaying.
为什么会发生这种情况?
Why is this happening?
public class RandomeCard {
public static void main(String[] args) {
int CardNumber = 54;
int i;
int Num;
int FirstNum=0;
int SecNum=0;
int ThirdNum=0;
int cnt = 1;
int numbersNeeded=0;
int max = 0;
for(i=1; i<=CardNumber; i++){
Num = (int)(Math.random()*54)+1;
if(i==1){
FirstNum = Num;
System.out.println("Fist card number "+FirstNum);
}
if(i==2){
SecNum = Num;
if(FirstNum == SecNum){
i++;
} else {
System.out.println("Second card number "+SecNum);
}
}
if(i==3){
ThirdNum = Num;
if(FirstNum == SecNum){
i++;
} else {
System.out.println("Third card number "+ThirdNum);
}
}
}
JFrame frame = new JFrame("Random Card Display");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setLayout(new GridLayout(1,3));
frame.setVisible(true);
ImageIcon icon = new ImageIcon("card/.png");
JLabel label = new JLabel(icon);
frame.add(label);
frame.add(new jlbl(new icon1("card/"+FirstNum+".png")));
frame.add(new jlbl(new icon1("card/"+SecNum+".png")));
frame.add(new jlbl(new icon1("card/"+ThirdNum+".png")));
}
private static class icon1 {
public icon1(String string) {
ImageIcon icon1 = new ImageIcon();
}
}
private static class jlbl extends PopupMenu {
public jlbl(icon1 icon1) {
JLabel jlbl = new JLabel();
}
}
}
推荐答案
您的所有类都没有绑定在一起。 icon1
加载 IconImage
,但随后不执行任何操作,创建 JLabel
in PopupMenu
,但不要将其添加到任何内容...
None of your classes bind together. icon1
loads an IconImage
, but then does nothing with it, you create a JLabel
in PopupMenu
, but don't add it to anything...
只需添加 JLabel
到 JFrame
frame.add(new JLabel(new ImageIcon("card/"+FirstNum+".png")));
这假设图像存储在名为 card $的目录中c $ c>与程序执行位于同一位置。
This assumes that the images are stored in a directory called card
which is located at the same location as the program is executed.
您可能会找到 ImageIO.read
加载图像的更好选择,至少在出现问题时抛出 IOException
。
You might find ImageIO.read
a better choice for loading images, at least it throws an IOException
when things go wrong.
Take a look at How to Use Labels and Reading/Loading an Image for more details
这篇关于GUI图像显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!