Hi, I am making a simple game,this is my first time to develop java game,but i think i am lost in my code,i could not display or show my bullet when i pressed arrow up,can you help me please how can i achieve on this.
here is my simple code.
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.*;
import java.util.List;
public class Mygame{
private Image ship;
private boolean up;
private boolean down;
private boolean right;
private boolean left;
private int posX = 300;
private int posY = 560;
Graphics2D g2d;
Thread gameloop;
Bullet bb = new Bullet();
Mypanel p = new Mypanel();
public Mygame(){
JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Mypanel panel = new Mypanel();
panel.setPreferredSize(new Dimension(600,600));
frame.add(panel);
frame.pack();
frame.setVisible(true);
panel.startGame();
}
class Mypanel extends JPanel{
private List <Bullet> bullets = new ArrayList <Bullet>();
public Mypanel() {
try {
ship = ImageIO.read(getClass().getResource("images/spaceship.png"));
} catch (IOException exc) {
exc.printStackTrace();
}
bullets = new ArrayList <Bullet>();
bullets.add(new Bullet(posX,posY));
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false),
"arrowUP");
getActionMap().put("arrowUP",
arrowUP);
Action arrowUP = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
up = true;
posY-=5;
repaint();
}
};
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.fillRect(0,0,600,600);
g2d.setColor(Color.BLACK);
g2d.drawImage(ship, posX, posY, null);
}
}
class Bullet{
final int speed = 2;
int x,y;
public Bullet(){}
Bullet(int x, int y){
this.x = x;
this.y = y;
}
public void setX(int x){
this.x = x;
}
public void setY(int y){
this.y=y;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public void moveForward(){
y-=speed;
}
}
public static void main(String []args) {
new Mygame();
}
}