简体   繁体   English

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

[英]How to draw and repaint an object class (JPanel)

I'm trying to create a game. 我正在尝试创建一个游戏。 I made a Person class: 我做了一个Person类:

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

and a Panel class: 和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) {}
  }
}

What this does right now is, when the program is run, it has a black circle in the middle of a white background, and whenever I press the up arrow key, the circle moves up. 现在的作用是,在运行该程序时,它在白色背景中间有一个黑色的圆圈,每当我按向上箭头键时,圆圈就会向上移动。

What I want it to do is somehow have Person be represented as a/the circle (for now), and whenever I press up, the Person (circle) is moving up, and Person's x and y properties to be changed accordingly as well. 我想要做的是以某种方式将Person表示为a /圆圈(现在),每当我按下时,Person(圆圈)都向上移动,并且Person的x和y属性也要相应地更改。

You can simply drop DrawPanel.x and DrawPanel.y and instead use x and y of DrawPanel.bill : 你可以简单地拖放DrawPanel.xDrawPanel.y ,而使用xyDrawPanel.bill

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

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

and

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

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

and

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM