Ugh, I'm sorry MadProgrammer but I just couldn't get the KeyBinding to work the way I wanted it to :(. But I'll keep looking at some more tutorials till I figure it out. For now though I've stuck to a KeyListener and it works. But now I'm having an issue where p.move(); doesn't actually move the player. All other code I've put in works fine except p.move();. I probably shouldn't be asking this many questions, so if you want me to stop just say so, but the whole SO community is really nice. Again, I'll post the code.
Main class:
import javax.swing.*;
public class Game extends JFrame{
public static void main(String[] args){
new Game();
}
public Game(){
add(new Board());
setTitle("Hi mom");
setSize(555,330);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(3);
setVisible(true);
}
}
Board Class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Board extends JPanel implements ActionListener {
Image background;
Player p;
boolean moving;
public Board() {
setFocusable(true);
requestFocus();
addKeyListener(new KeyInputEvents());
Timer timer = new Timer(25, this);
timer.start();
ImageIcon img = new ImageIcon(getClass().getResource("images/map.png"));
background = img.getImage();
p = new Player();
}
public void paint(Graphics g) {
g.drawImage(background, 0, 0, null);
g.drawImage(p.getPlayer(), p.getX(), p.getY(), null);
}
public void actionPerformed(ActionEvent e) {
repaint();
}
public JPanel getBoard(){
return this;
}
)
Player Class (This is probably where stuff goes wrong):
import javax.swing.*;
import java.awt.*;
public class Player{
int x = 30;
int y = 187;
Image player;
public Player(){
ImageIcon img = new ImageIcon(getClass().getResource("images/player.png"));
player = img.getImage();
}
public Image getPlayer(){
return player;
}
public void move(int x, int y){
this.x += x;
this.y += y;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
)
KeyInputEvents Class:
import java.awt.event.*;
import javax.swing.*;
public class KeyInputEvents extends KeyAdapter implements ActionListener{
int k;
boolean moving = true;
Player p = new Player();
public KeyInputEvents(){
Timer timer = new Timer(25,this);
timer.start();
}
public void keyPressed(KeyEvent e){
k = e.getKeyCode();
moving = true;
}
public void keyReleased(KeyEvent e){
moving = false;
}
public void actionPerformed(ActionEvent e) {
if(k == 'D' && moving == true){p.move(5,0);}
if(k == 'A' && moving == true){p.move(-5,0);}
}
}