I'm a beginner at java and I'm trying to make a square that moves in response to arrow keys. I've tried a lot of things but it just won't work. There are probably obvious errors in my code/ in my understanding of the code so if anyone could point them out that would be really helpful. Main class: import java.awt.; import javax.swing.;
public class mainClass2 {
public static void main(String[] args) {
JFrame window = new JFrame();
window.setSize(600,400);
window.setVisible(true);
window.getContentPane().setBackground(Color.WHITE);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
boolean constant = true;
graphics2 DC = new graphics2();
window.add(DC);}
}
Graphics class:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class graphics2 extends JComponent implements KeyListener{
public static int x1;
public static int y1;
public static int xvelocity = 0;
public static int yvelocity = 0;
public void paintComponent(Graphics g){
graphics2 thing = new graphics2();
this.addKeyListener(thing);
System.out.println(x1);
System.out.println(y1);
Graphics2D g2 =(Graphics2D)g;
Rectangle rect = new Rectangle(x1,y1,200,200);
g2.setColor(Color.red);
rect.setLocation(x1,y1);
g2.fill(rect);
repaint();
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
x1+=10;
// TODO Auto-generated method stub
if(e.getKeyCode()== KeyEvent.VK_LEFT) {
x1-=10;
}
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}