Java ball moving

匿名 (未验证) 提交于 2019-12-03 01:44:01

问题:

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!

回答1:

  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.



文章来源: Java ball moving
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!