user2577576
user2577576

Reputation:

Why isnt my repaint working?

I have the code:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class obj_Dingus 
extends Applet
implements KeyListener{

    private Rectangle rect; //The rectangle that we move 

    public void init()
    {
        this.addKeyListener(this);
        rect = new Rectangle(0, 0, 50, 50);
    }

    public void paint(Graphics g)
    {
        setSize(500,500);
        Graphics2D g2 = (Graphics2D)g;
        g2.fill(rect);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        repaint();
        if (e.getKeyCode() == KeyEvent.VK_RIGHT){
            rect.setLocation(rect.x + 2, rect.y);
        }  if (e.getKeyCode() == KeyEvent.VK_LEFT){
            rect.setLocation(rect.x - 2, rect.y);
        }  if (e.getKeyCode() == KeyEvent.VK_UP){
            rect.setLocation(rect.x, rect.y - 2);
        }  if (e.getKeyCode() == KeyEvent.VK_DOWN){
            rect.setLocation(rect.x, rect.y + 2);
        }
        repaint();
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }
}

As far as I can tell, it should make a black box that is moved around the screen, but instead the screen is not updated, and the old boxes are not cleared. It ends up with a giant black line on the screen, and I have no idea what I am doing wrong, I am a total beginner.

Upvotes: 2

Views: 65

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168825

public void paint(Graphics g)
{
    setSize(500,500);
    Graphics2D g2 = (Graphics2D)g;
    g2.fill(rect);
}

Never call anything in the paint(Graphics) method that might cause the GUI to repaint(). Adding components, changing the content of components, or setting the size of a GUI all trigger repaint(), so this applet goes into an infinite loop.

It should be more along the lines of:

public void paint(Graphics g)
{
    super.paint(g); // always call the parent method 1st..
    Graphics2D g2 = (Graphics2D)g;
    g2.fill(rect);
}

Upvotes: 1

Related Questions