当我运行我的程序时,一切都按计划进行,除了我必须更改屏幕上的卡片的按钮直到鼠标悬停才会出现。我假设这是因为保存图像的任何容器都在它上面,但我不知道如何将它移动到背景中,甚至不知道我可以使用哪种容器来添加图像。
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.util.Random;
import java.awt.event.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
public class oneplayer extends JFrame {
BufferedImage image1, image2, image3, image4;
Random gen = new Random();
public void redo() {
int p1, p2, p3, p4;
p1 = gen.nextInt(13) + 1;
p2 = gen.nextInt(13) + 14;
p3 = gen.nextInt(13) + 27;
p4 = gen.nextInt(13) + 40;
try {
File input1 = new File("C:/Users/Mike/Desktop/eclipse/workspace/inClass/src/" + p1 + ".png");
File input2 = new File("C:/Users/Mike/Desktop/eclipse/workspace/inClass/src/" + p2 + ".png");
File input3 = new File("C:/Users/Mike/Desktop/eclipse/workspace/inClass/src/" + p3 + ".png");
File input4 = new File("C:/Users/Mike/Desktop/eclipse/workspace/inClass/src/" + p4 + ".png");
image1 = ImageIO.read(input1);
image2 = ImageIO.read(input2);
image3 = ImageIO.read(input3);
image4 = ImageIO.read(input4);
} catch (IOException ie) {
System.out.println("Error:"+ie.getMessage());
}
repaint();
}
public oneplayer() {
JPanel buttonPanel = new JPanel();
setLayout(new BorderLayout());
JButton refresh = new JButton("Refresh");
refresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
redo();
}
});
add(buttonPanel, BorderLayout.SOUTH);
buttonPanel.add(refresh, BorderLayout.CENTER);
redo();
}
public void paint(Graphics g) {
g.drawImage(image1, 20, 55, null);
g.drawImage(image2, 96, 55, null);
g.drawImage(image3, 172, 55, null);
g.drawImage(image4, 248, 55, null);
}
public static void main(String args[]) {
oneplayer frame = new oneplayer();
frame.setTitle("Random Cards");
frame.setSize(350, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}