我需要对程序进行编码,以便从一副纸牌中随机选择三张纸牌。图像位于我的桌面上的文件夹中。然后,我显示卡的图像。我的程序可以正常运行,只要读取文件,然后从52个文件中随机挑选3张即可。我让程序在输出中打印3张随机的卡片。但是当我的计算机上打开Java窗口时,我看不到卡的图像。它显示一条细线,不断重复。因此,我认为它正在尝试显示卡,但是在某处出现问题,导致无法显示整个卡。 预先感谢您的帮助!
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class DisplayThreeCards {
public static void main(String[] args) {
// File location
File folder = new File("//Users//macuser//Desktop//DeckOfCards");
File[] fileList;
fileList = folder.listFiles();
// Generate random card. Uses the Math.rand() function.
// The '%' operator is used to make sure the random is between 0-52.
int randomCard = (int) (Math.random() * 1000);
System.out.println(fileList[randomCard % 52].getAbsolutePath());
// Print the filename.
// Card 1
System.out.println(fileList[randomCard % 52].getName());
randomCard = (int) (Math.random() * 1000);
// Card 2
System.out.println(fileList[randomCard % 52].getName());
randomCard = (int) (Math.random() * 1000);
// Card 3
System.out.println(fileList[randomCard % 52].getName());
randomCard = (int) (Math.random() * 1000);
try {
ImageFrame frame = new ImageFrame(fileList[randomCard % 52].getAbsolutePath());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
} catch (Exception E) {
}
// Create a window for the card images to be displayed
class ImageFrame extends JFrame {
public ImageFrame(String name) {
setTitle("ImageTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
ImageComponent component = new ImageComponent(name);
add(component);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 300;
}
class ImageComponent extends JComponent {
private static final long serialVersionUID = 1L;
private Image image;
public ImageComponent(String name) {
try {
File image2 = new File(name);
image = ImageIO.read(image2);
} catch (IOException e) {
}
}
@Override
public void paintComponent(Graphics g) {
if (image == null) {
}
int imageWidth = image.getWidth(this);
int imageHeight = image.getHeight(this);
g.drawImage(image, 50, 50, this);
for (int i = 0; i * imageWidth <= getWidth(); i++) {
for (int j = 0; j * imageHeight <= getHeight(); j++) {
if (i + j > 0) {
g.copyArea(0, 0, imageWidth, imageHeight, i * imageWidth, j * imageHeight);
}
}
}
}
}
}
}