[英]Can't figure out how to get rid of a graphic when I figure hit a button
我試圖做到這一點,所以當您按下按鈕時,您會破壞某些東西,但是我無法讓敵人消失(紅色方塊)。這是圖形的代碼:
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Ellipse2D P1 = (new Ellipse2D.Double(x, y, 40, 40));
Rectangle2D P2 = (new Rectangle2D.Double(x2, y2, 40, 40));
g2.fill(P1);
g2.setPaint(Color.RED);
g2.fill(P2);
}
使用這種鍵綁定方法,如何使Rectangle2D消失?
public void actionPerformed(ActionEvent e) {
repaint();
x += velx;
y += vely;
x2 += velx2;
y2 += vely2;
}
public void up() {
vely = -2;
velx = 0;
}
public void down() {
vely = 2;
velx = 0;
}
public void left() {
vely = 0;
velx = -2;
}
public void right() {
vely = 0;
velx = 2;
}
public void stop() {
vely = 0;
velx = 0;
}
public void stop2() {
vely2 = 0;
velx2 = 0;
}
public void up2() {
vely2 = -2;
velx2 = 0;
}
public void down2() {
vely2 = 2;
velx2 = 0;
}
public void left2() {
vely2 = 0;
velx2 = -2;
}
public void right2() {
vely2 = 0;
velx2 = 2;
}
public void attack() {
if (x <= x2+100 && y <= y2+100){
}
}
//public void attack() {
//
//}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if(code == KeyEvent.VK_UP){
up();
}
if(code == KeyEvent.VK_DOWN){
down();
}
if(code == KeyEvent.VK_LEFT){
left();
}
if(code == KeyEvent.VK_RIGHT){
right();
}
if(code == KeyEvent.VK_W){
up2();
}
if(code == KeyEvent.VK_S){
down2();
}
if(code == KeyEvent.VK_A){
left2();
}
if(code == KeyEvent.VK_D){
right2();
}
if(code == KeyEvent.VK_P){
stop();
}
if(code == KeyEvent.VK_O){
stop2();
}
if(code == KeyEvent.VK_Z){
attack();
}
}
與其創建要在paintComponent
方法本身內繪制的對象,不如維護要渲染的對象的集合並在每個paintComponent
調用中遍歷該集合。 然后只需從集合中刪除即可“銷毀” P2對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.