I am a beginner Java programmer, working on a very simple game. I have learned the basics of OOP and am trying to test & expand my knowledge.
In my game, there is a projectile object. The game takes place inside a JFrame.
How would I display the projectile object visually inside the JFrame? I would like to use an image/picture. I essentially want to 'attach' an image to the projectile object.
Main Class
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());
}
}
Projectile Class
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);
}
}