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.
Recommendations:
g.drawRect(250, 250, 10, 10);
, have g.drawRect(rectX, rectY, rectW, rectH);
. Edit , As you yourself suggest, "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."
setRectX(int rectX)
, setRectY(int rectY)
, etc...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.