目前我试图在keyevent更新我的矩形位置,但我不知道如何从另一个类调用paintComponent方法或如何实现这个
绘制类
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);
}
}
我的听众班
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);
}
}
我尝试在名为paintComponent的侦听器类中添加一个方法,但我需要传递一个图形对象..不知道如何实现这一点。
我正在考虑使用变量绘制一个矩形,并在keyevent修改变量,但我不知道这是否是正确的方法。
答案 0 :(得分:2)
建议:
g.drawRect(250, 250, 10, 10);
,g.drawRect(rectX, rectY, rectW, rectH);
。 修改,正如您自己所建议的那样,"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)
等......