GUI图像显示

时间:2015-05-26 07:11:46

标签: java swing user-interface random

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

为什么会这样?

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

}

1 个答案:

答案 0 :(得分:3)

没有一个类绑定在一起。 icon1加载了IconImage,但随后无效,您在JLabel中创建PopupMenu,但不将其添加到任何内容中......

只需将JLabel添加到JFrame

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

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

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

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