Whats wrong with my code? I tried several things but it still won't work!
Whats wrong with this code?
I Tried everything but " super.paintComponent(g); " part still gives the same error
" - The method paintComponent(Graphics) is undefinedfor the type KeyAdapter "
Code :
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Keying extends JPanel{
public Rectangle character;
public int charW= 24;
public int charH = 36;
public boolean right = false;
public boolean left = false;
public Keying(Display f, Images i){
character = new Rectangle(180, 180, charW, charH);
f.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_D){
right = true;
character.x +=1;
}
if(e.getKeyCode() == KeyEvent.VK_A){
left = true;
character.x -= 1;
}
}
public void keyReleased(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_D);
right = false;
if(e.getKeyCode() == KeyEvent.VK_A){
right = false;
}
};
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.DARK_GRAY);
g.setColor(Color.WHITE);
g.fillRect(character.x, character.y, character.width, character.height);
if(right){
character.x +=1;
}
if(left){
character.x -=1;
}
repaint();
}
private void setBackground(Color darkGray) {
}
{
}
});
}}
Re: Whats wrong with my code? I tried several things but it still won't work!
Quote:
he method paintComponent(Graphics) is undefinedfor the type KeyAdapter
The compiler is saying that the super class for the KeyAdapter class does not have a paintComponent() method.
Is the paintComponent() method in the code defined in the correct class?
To be sure that the class has a method that can be overridden, add a @Override statement on the line just before the method definition. That asks the compiler to check if the class that the method is in has a method with that name and args.
One big problem with the code is its poor formatting. The { and }s are not properly positioned to show nested code. Fixing that will show you what the problem is.