[英]How to draw and repaint an object class (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表示為a /圓圈(現在),每當我按下時,Person(圓圈)都向上移動,並且Person的x和y屬性也要相應地更改。
你可以簡單地拖放DrawPanel.x
和DrawPanel.y
,而使用x
和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);
}
和
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.