我是一名初學Java程序員,在一個非常簡單的遊戲上工作。我已經學會了面向對象的基礎知識,並試圖測試&擴展我的知識。如何將圖像附加到對象?
在我的遊戲中,有一個拋射物體。遊戲發生在JFrame內部。
我該如何在JFrame內部直觀地顯示拋射物體?我想使用圖片/圖片。我基本上想要將圖像附加到拋射物體上。
主類
public class MathGame implements ActionListener {
private static JButton[] choices = new JButton[4];
private static JLabel[] options = new JLabel[4];
private static double[] nums = new double[4];
public static JPanel container;
public static void main(String[] args) {
// frame
JFrame frame = new JFrame("Math Game");
frame.setSize(300, 500);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// container
container = new JPanel();
container.setLayout(null);
frame.setContentPane(container);
// title
JLabel title = new JLabel("Math Game");
title.setBounds(113, 10, 80, 15);
// option labels
for (int i = 0; i < choices.length; i++) {
options[i] = new JLabel("", SwingConstants.CENTER);
options[i].setBounds(5 + (72 * i), 50, 68, 68);
nums[i] = (int) (Math.random() * 100);
options[i].setText(Double.toString(nums[i]));
options[i].setOpaque(true);
options[i].setBackground(Color.RED);
}
// buttons
for (int i = 0; i < choices.length; i++) {
choices[i] = new JButton();
choices[i].setBounds(5 + (72 * i), 420, 68, 20);
choices[i].addActionListener(new MathGame());
container.add(choices[i]);
}
// progress bar
JProgressBar progress = new JProgressBar();
progress.setBounds(5, 450, 284, 20);
progress.setValue(0);
progress.setBackground(Color.LIGHT_GRAY);
progress.setStringPainted(true);
// adding it all
for (int i = 0; i < choices.length; i++) {
container.add(choices[i]);
container.add(options[i]);
}
container.add(title);
container.add(progress);
// extras
frame.toFront();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
Projectile bullet = new Projectile(150, 250);
System.out.println(bullet.toString());
}
}
彈丸類
public class Projectile extends Piece {
public Projectile(int x, int y) {
super(x, y);
}
public void fire() {
for (int i = 0; i < 10; i++) {
this.yPos = this.yPos - 5;
}
}
public void draw(Graphics2D g2)
throws IOException {
BufferedImage image = ImageIO.read(new File("C:\\Users\\jbakos\\Desktop\\pew.png"));
g2.drawImage(image, this.xPos, this.yPos, null);
}
}
請勿讀取圖形代碼中的圖像。在構建GUI時閱讀您的圖像。從磁盤讀取圖像比在繪圖JPanel上繪製圖像慢1000倍。 –