利用Swing做的简单的习题(二)

题目:

*12.9 (游戏: 显示三张牌)显示包含三个标签的框架。每个标签显示一张牌,牌的图像文件命名为1.png, 2.png,3png,并且存储在images目录中。这三张牌是不同的并且是随机选取的。

效果:

在这里插入图片描述

在这里插入图片描述

每次打开都是随机放置图片的。

代码如下:

package Test;

import com.sun.org.apache.xerces.internal.util.SynchronizedSymbolTable;

import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class Exercise12_9 extends JFrame {
    public Exercise12_9(){
        setLayout(new GridLayout(1,3));

        int a=(int)(Math.random()*3+1);
        int b=(int)(Math.random()*3+1);
        while(b==a){
             b=(int)(Math.random()*3+1);
    }
        int c=(int)(Math.random()*3+1);
        while(c==a||c==b){
            c=(int)(Math.random()*3+1);
        }



        JLabel label1=new JLabel();
        label1.setIcon(new ImageIcon(ClassLoader.getSystemResource("images/"+a+".png")));
        add(label1);

        JLabel label2=new JLabel();
        label2.setIcon(new ImageIcon(ClassLoader.getSystemResource("images/"+b+".png")));
        add(label2);

        JLabel label3=new JLabel();
        label3.setIcon(new ImageIcon(ClassLoader.getSystemResource("images/"+c+".png")));
        add(label3);


    }

    public static void main(String[] args) {
        Exercise12_9 frame=new Exercise12_9();
        frame.setTitle("Exercise12_9");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800,500);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

    }

}

思路分析

	  int a=(int)(Math.random()*3+1);
    int b=(int)(Math.random()*3+1);
    while(b==a){
         b=(int)(Math.random()*3+1);
}
    int c=(int)(Math.random()*3+1);
    while(c==a||c==b){
        c=(int)(Math.random()*3+1);
    }

因为每次打开的图片顺序都要唯一且不相同,所以用了各不相同的三个随机数,在文件路径里面插入这三个随机数。因为图片是以数字命名的,所以每次出现的时候都是不一样的图片。

    label1.setIcon(new ImageIcon(ClassLoader.getSystemResource("images/"+a+".png")));

设置标签内的图片

ClassLoader.getSystemResource("images/"+a+".png"))

设置图片路径

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值