用JAVA编写,随机产生1到10张图片,输入出现图片数量,判...
发布网友
发布时间:2023-10-28 14:01
我来回答
共1个回答
热心网友
时间:2024-05-25 20:21
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class RandomImage extends JFrame{
private JLabel[] labels;
private Random r;
private int x;
private JPanel p;
public RandomImage() {
r = new Random();
x = r.nextInt(10);
labels = new JLabel[x];
for(int i = 0; i < x; i++){
BufferedImage bi = new BufferedImage(60,30,BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.setColor(Color.RED);
g.setFont(new Font(null,Font.BOLD,i+10));
g.drawString("图片"+i, 10, 20);
ImageIcon icon = new ImageIcon(bi);
labels[i] = new JLabel(icon);
}
p = new JPanel();
}
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
RandomImage ri = new RandomImage();
try {
while(true){
System.out.println("请猜猜一共有多少张图片:");
int in = Integer.parseInt(reader.readLine());
if(in == ri.x){
System.out.println("恭喜你才对了!");
for(int i = 0; i < ri.labels.length; i++){
ri.p.add(ri.labels[i]);
}
ri.add(ri.p);
ri.setVisible(true);
ri.pack();
ri.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
break;
}else{
System.out.println("抱歉您猜错了!");
}
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}