0
這裏的問題是paintComponent()方法被調用,它獲取fillRect()的必要變量,但在按下按鍵後實際不會繪製任何東西。我不明白爲什麼每次按下D鍵時,mato.getPositionX()的返回值都會增加,並且遞增的值傳遞給fillRect()。下面的代碼:繪製方法被調用但不重繪
Screen類
public class Screen extends JFrame implements KeyListener {
private Mato mDrawScreensMato;
public Screen() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
setLocationRelativeTo(null);
setSize(400, 400);
DrawScreen screen = new DrawScreen();
mDrawScreensMato = screen.getMato();
addKeyListener(this);
add(screen);
}
//keyTyped
@Override
public void keyPressed(KeyEvent ke) {
int c = ke.getKeyCode();
if (c == KeyEvent.VK_D) {
mDrawScreensMato.setPositionX(mDrawScreensMato.getPositionX() + 1);
repaint();
}
}
//keyReleased
}
DrawScreen類
public class DrawScreen extends JPanel {
private Mato mato;
public DrawScreen() {
mato = new Mato();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
System.out.println(mato.getPositionX());
g2d.fillRect(
mato.getPositionX(), mato.getPositionY(),
mato.MATO_WIDTH, mato.MATO_HEIGHT
);
}
public Mato getMato() {
return mato;
}
}
馬託格羅索類
public class Mato {
final int MATO_WIDTH = 20;
final int MATO_HEIGHT = 20;
final int MATO_START_POS_X = 20;
final int MATO_START_POS_Y = 40;
private int positionX;
private int positionY;
public Mato(){
positionX = MATO_START_POS_X;
positionY = MATO_START_POS_Y;
}
public void setPositionX(int positionX) {
this.positionX = positionX;
}
public int getPositionX() {
return positionX;
}
//Get/Set positionY
}
的發佈代碼似乎工作確定後,一些編譯問題由於丟失/註釋掉的方法而被解決。試着發佈一個能夠證明問題的[完整示例](http://stackoverflow.com/help/mcve)。另外,要避免使用鍵監聽器並使用鍵綁定,請參閱[如何使用鍵綁定](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html)以獲取更多詳細信息。 – tenorsax