2015-11-07 68 views
0

我正在嘗試創建一個遊戲。我做了一個Person類:如何繪製和重繪對象類(JPanel)

public class Person { 
    public int x; 
    public int y; 
    public int orientation; 
} 

和麪板類:

public class DrawPanel extends JPanel { 

    private int x = 225; 
    private int y = 225; 
    private Person bill = new Person(); 

    public DrawPanel() { 
    setBackground(Color.white); 
    setPreferredSize(new Dimension(500, 500)); 

    addKeyListener(new Keys()); 
    setFocusable(true); 
    requestFocusInWindow(); 
    } 

    public void paintComponent(Graphics page) { 
    super.paintComponent(page); 

    page.setColor(Color.black); 
    page.fillOval(x, y, 50, 50); 
    } 

    private class Keys implements KeyListener { 
    public void keyPressed(KeyEvent e) { 
     int key = e.getKeyCode(); 
     if (key == KeyEvent.VK_UP) { 
      bill.orientation = 0; 
      y = y - 10; 
      repaint(); 
     } 
    } 

    public void keyReleased(KeyEvent arg0) {} 

    public void keyTyped(KeyEvent arg0) {} 
    } 
} 

這樣做現在的問題是,當程序運行什麼,它有一個白色的背景中間的黑色圓圈,每當我按下向上箭頭鍵,圓圈向上移動。

我想讓它做的事情是讓某人被表現爲一個圓圈(現在),並且每當我按下時,人物(圓圈)向上移動,人物的x和y屬性被改變因此也是如此。

回答

0

你可以簡單地拖放DrawPanel.xDrawPanel.y,而使用xDrawPanel.billy

public class DrawPanel extends JPanel { 
    private Person bill = new Person(); 

    public DrawPanel() { 
     bill.x = bill.y = 225; 
     ... 

public void paintComponent(Graphics page) { 
    super.paintComponent(page); 

    page.setColor(Color.black); 
    page.fillOval(bill.x, bill.y, 50, 50); 
} 

public void keyPressed(KeyEvent e) { 
    int key = e.getKeyCode(); 
    if (key == KeyEvent.VK_UP) { 
     bill.orientation = 0; 
     bill.y -= 10; 
     repaint(); 
    } 
} 
+0

哇感謝:d,這是一個比我想象的要容易得多 – failninja21