2

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.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1) Why code an applet? If it is due due to spec. by teacher, please refer them to [Why CS teachers should stop teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) Why AWT rather than Swing? See this answer on [Swing extras over AWT](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon using AWT components. If you need to support older AWT based APIs, see [Mixing Heavyweight and Lightweight Components](http://www.oracle.com/technetwork/articles/java/mixing-components-433992.html). – Andrew Thompson Jul 12 '13 at 18:54
  • In paint can you do g2.clearRect(); – eliteslayer Jul 12 '13 at 18:58

1 Answers1

1
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);
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433