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){}
}