Currently Im trying to update my rectangle position at keyevent but I dont know how to call the paintComponent method from another class or how to achieve this
Paint class
package com.raggaer.frame;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Elements extends JPanel {
public Elements() {
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(250, 250, 10, 10);
}
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
}
And my listener class
package com.raggaer.frame;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Listener implements KeyListener {
public void keyPressed(KeyEvent e) {
System.out.println(e.getExtendedKeyCode());
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void paintComponent(Graphics g) {
g.drawRect(10, 10, 20, 20);
}
}
I tried adding a method inside the listener class called paintComponent but I need to pass a graphic object.. dont know how to achieve this.
I was thinking on drawing a rectangle using variables and at keyevent modify that variables but I dont know if thats the correct way to do it.