Java 如何绘制和重新绘制对象类(JPanel)
我正在尝试创建一个游戏。我做了一个人课:Java 如何绘制和重新绘制对象类(JPanel),java,graphics,jpanel,Java,Graphics,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 Dra
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) {}
}
}
现在这样做的是,当程序运行时,它在白色背景的中间有一个黑色圆圈,每当我按下向上箭头键,圆圈就会向上移动
我想要它做的是,让人以某种方式被表示为一个/圆圈(现在),每当我向上按时,这个人(圆圈)就会向上移动,您可以简单地删除
DrawPanel.x
和DrawPanel.y
,而使用DrawPanel.bill的x
和y
:
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();
}
}