Java绘图问题

时间:2014-04-18 13:01:37

标签: java drawing

这段代码应该是简单的java游戏。有一个绿色可移动的矩形(播放器)和其他几个矩形(敌人)。我已经为框架设置了关键监听器,所以绿色矩形可以是但是要改变玩家的sx和y coords是显而易见的,我必须在paintCoponent方法中调用重绘。当我这样做时,我可以移动绿色rect但在新坐标上再次生成其他矩形。如何阻止这种不受欢迎的影响?

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 个答案:

答案 0 :(得分:1)

代码不会显示您描述的行为。

但是,您有两个单独的绘图实例:

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

删除顶部的一个并使用 main 中的一个:

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

此外,不要在 paintComponent(Graphics)中调用 repaint(),因为这将持续生成绘制调用。在对状态进行一些修改后调用它 - 例如在 keyPressed(KeyEvent)

另见Painting in AWT and Swing