如何绘制和重新绘制对象 class (JPanel)

How to draw and repaint an object class (JPanel)

我正在尝试创建游戏。我做了一个人 class:

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

和一个小组 class:

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) {}
  }
}

现在做的是,当程序是运行时,它在白色背景中间有一个黑色圆圈,每当我按下向上箭头键时,圆圈就会向上移动。

我想要它做的是以某种方式将 Person 表示为 a/the 圆圈(目前),每当我向上按时,Person(圆圈)向上移动,Person 的 x 和 y 属性也相应地改变。

您可以简单地删除 DrawPanel.xDrawPanel.y 并使用 xy of DrawPanel.bill:

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();
    }
}