Java ball moving

2019-09-04 13:35发布

My problem is that the ball turns into a line once moved.
Here is the code:

package Java;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.*;

public class javagame extends JFrame {

    private Image dbImage;
    private Graphics dbg;

    int x, y;

    public class AL extends KeyAdapter {
        public void keyPressed (KeyEvent e) {

            int keyCode = e.getKeyCode();
            if(keyCode == e.VK_LEFT) {
                x-= 5;
            }
            if(keyCode == e.VK_RIGHT) {
                x+= 5;
            }
            if(keyCode == e.VK_UP) {
                y-= 5;
            }
            if(keyCode == e.VK_DOWN) {
                y+= 5;
            }
        }
        public void keyReleased (KeyEvent e) {
        }
    }

    public javagame() {
        addKeyListener(new AL());

        setTitle("Java Game");
        setSize(750, 750);
        setResizable(false);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        x = 250;
        y = 250;
    }

    public void paint(Graphics g) {
        dbImage = createImage(getWidth(), getHeight());
        dbg = dbImage.getGraphics();
        paintCompenent(dbg);
        g.drawImage(dbImage, 0, 0, this);
    }

    public void paintComponent (Graphics g){
        g.drawString("Copy Right All rights reserved to Aaron Collins 2013-2013", 275, 100);
        g.drawLine(270, 105, 415, 105);

        g.fillOval(x, y, 15, 15);

        repaint();
    }

    public static void main(String[] args) {
        new javagame();
    }
}

When I say it turns into a line, I mean the ball moves but does not remove the previous one.
Please help me resolve the problem so I can continue with my game!

标签: java line
1条回答
啃猪蹄的小仙女
2楼-- · 2019-09-04 14:11
  1. You override paint, but never call super.paint, meaning that component never prepares the Graphics context for a new paint cycle, meaning that what ever you painted before remains
  2. Your paintComponent method will never be called because JFrame does not support this method
  3. You should not be performing custom painting on a top level container (like JFrame), but should be using something like JPanel and override it's paintComponent method (making sure you call super.paintComponent first).
  4. You should also avoid calling any method that may trigger a repaint in any paintXxx method you're overriding...like repaint

The Graphics context is a shared resource, that means that the Graphics context you are given was used to paint all the other components in UI before you. paintComponent is responsible for preparing the Graphics context for painting by clearing the area it wants to paint in.

I'd recommend that you take a read through Custom Painting

I would also avoid KeyListener and use the Key Bindings API instead.

查看更多
登录 后发表回答