【问题标题】:GUI image displayGUI图像显示
【发布时间】:2015-05-26 07:11:45
【问题描述】:

这是我为显示随机卡片而编写的代码。随机卡选择工作正常,但图像未显示。

为什么会这样?

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();
    }
}

}

【问题讨论】:

  • 为什么要混合命令行和 GUI 代码?与源相关的图像存储在哪里?你为什么要扩展PopupMenu?为什么不直接将JLabel 添加到JFrame

标签: java swing user-interface random


【解决方案1】:

您的所有类都没有绑定在一起。 icon1 加载了一个IconImage,但随后什么也不做,你在PopupMenu 中创建了一个JLabel,但不要将它添加到任何东西......

只需将JLabel 添加到JFrame

frame.add(new JLabel(new ImageIcon("card/"+FirstNum+".png")));

这假定图像存储在名为card 的目录中,该目录与程序执行的位置相同。

您可能会发现ImageIO.read 是加载图像的更好选择,至少当出现问题时它会抛出IOException

查看How to Use LabelsReading/Loading an Image 了解更多详情

【讨论】:

  • 谢谢。我试过你的代码,但它不工作,静止图像不显示
  • 正如我所说的“这假设图像存储在一个名为 card 的目录中,该目录与程序执行的位置相同” - 因为我不知道您的图像存储在哪里,这是我能做的最好的事情
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-20
  • 1970-01-01
相关资源
最近更新 更多