2014-03-12 66 views
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 

} 
+1

的發佈代碼似乎工作確定後,一些編譯問題由於丟失/註釋掉的方法而被解決。試着發佈一個能夠證明問題的[完整示例](http://stackoverflow.com/help/mcve)。另外,要避免使用鍵監聽器並使用鍵綁定,請參閱[如何使用鍵綁定](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html)以獲取更多詳細信息。 – tenorsax

回答

1

你的問題的主要原因是,你在呼喚setVisible早.. 。

一般的經驗法則是,打電話setVisible您準備了UI

public Screen() { 
    DrawScreen screen = new DrawScreen(); 
    mDrawScreensMato = screen.getMato(); 
    addKeyListener(this); 
    add(screen); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    // This is a useless call as DrawScreen 
    // does not provide appropriate sizing hints to the layout manager 
    pack(); 
    setSize(400, 400); 
    // This needs to be called AFTER the size of window has been determined, 
    // as it uses the size of the window to determine it's location 
    setLocationRelativeTo(null); 
    setVisible(true); 
} 

KeyListener是出了名的麻煩只是以後,你會更好地使用Key Bindings