2014-04-18 138 views
0

這段代碼應該是簡單的java遊戲。有一個綠色的可移動矩形(玩家)和其他幾個矩形(敵人)。我設置了框架的關鍵偵聽器,所以綠色的矩形可以移動。爲了讓玩家的x和y座標變化明顯,我必須在paintCoponent方法中調用repaint。當我這樣做時,我可以移動綠色矩形,但是其他矩形會在新座標上再次生成。如何停止這種不希望的效果?Java繪圖問題

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.KeyEvent; 
import java.awt.event.KeyListener; 
import java.util.Random; 

public class Drawing extends JPanel implements KeyListener 
{ 
public static JFrame frame; 
public static int[] x=new int[10]; 
public static int[] y=new int[10]; 
public static int a; 
public static Random random; 
public static int p_x=0; 
public static int p_y=0; 

public static void drawframe(int width,int height) 
{ 
    frame=new JFrame("The game"); 
    frame.setSize(width,height); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 
    frame.setResizable(false); 
    frame.addKeyListener(new Drawing()); 
} 

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

    drawenemies(g,6); 
    setradius(g); 
    setplayer(g); 
} 

public void drawenemies(Graphics g,int amount) 
{ 
    random=new Random(); 
    a=amount; 

    for(int i=1;i<=amount;i++) 
    { 
     x[i]=random.nextInt(frame.getWidth()); 
     y[i]=random.nextInt(frame.getHeight()); 

     g.fillRect(x[i], y[i], 20, 20); 
    } 
} 

public void setradius(Graphics g) 
{ 
    g.setColor(Color.RED); 

    for(int i=1;i<=a;i++) 
    { 
     g.drawRect(x[i]-15, y[i]-15, 50, 50); 
    } 
} 

public void setplayer(Graphics g) 
{ 
    g.setColor(Color.GREEN); 
    g.fillRect(p_x, p_y, 20, 20); 
} 

public static void main(String args[]) 
{ 
    drawframe(500,500); 
    Drawing instance=new Drawing(); 
    frame.add(instance); 

} 

@Override 
public void keyPressed(KeyEvent e) 
{ 
    if(e.getKeyCode()==39) 
    { 
     p_x=p_x+10; 
    } 
} 




public void keyReleased(KeyEvent arg0){} 
public void keyTyped(KeyEvent arg0){} 

} 

回答

1

代碼沒有顯示您描述的行爲。

但是,你有兩個單獨的實例繪製

frame.addKeyListener(new Drawing()); 
//.... 
Drawing instance=new Drawing(); 

取出最上面的一個,並使用一個在主要

Drawing instance=new Drawing(); 
frame.add(instance); 
frame.addKeyListener(instance); 

另外,不要叫重繪() in paintComponent(Graphics),因爲這將不斷生成繪畫調用。在對狀態進行一些修改後調用它 - 例如在keyPressed(KeyEvent)

另請參閱Painting in AWT and Swing