Question

This code is supposed to be simple java game.There's one green moveable rectangle (player) and few other rectangles (enemies).I've set up key listener for frame, so green rectangle can be moveable.But to make change of player's x and y coords noticeable, I have to call repaint in paintCoponent method.When I do so I can move green rect but other rectangles are being generated over again on new coordinates.How to I stop this unwished effect?

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

}
Was it helpful?

Solution

The code does not exhibit the behavior you describe.

However, you have two separate instances of Drawing:

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

Remove the top one and use the one in main:

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

Also, do not call repaint() in paintComponent(Graphics) as this will continuously generate paint calls. Call it after you make some modification to state - e.g. in keyPressed(KeyEvent).

See also Painting in AWT and Swing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top