如何绘制和重绘对象类(JPanel)

时间:2015-11-07 12:24:13

标签: java graphics jpanel

我正在尝试制作游戏。我做了一个Person课程:

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

和Panel类:

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表示为/圆(现在),每当我按下时,Person(圆圈)向上移动,Person的x和y属性相应地改变同样。

1 个答案:

答案 0 :(得分:0)

您只需删除DrawPanel.xDrawPanel.y,然后使用x的{​​{1}}和y

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