题目:
*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"))
设置图片路径