日期:2014-05-20  浏览次数:20644 次

关于 java 移动小球 问题....快崩溃咯..

package com.练习;

import java.awt.*;

import javax.swing.*;
import java.awt.event.*;

public class Box
{
     public static void main(String[] args)
     {
          new MyFrame();
     }
}
class MyFrame extends JFrame
{
     MyPanel mp = null;
     public MyFrame()
     {
          mp = new MyPanel();
          this.add(mp);
          this.setSize(400, 300);
          this.setVisible(true);
          this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     }
}
class MyPanel extends JPanel implements Runnable
{
     int x = 100, y = 100;
     public MyPanel()
     {
     }
     public void paint(Graphics g)
     {
          super.paint(g);
          g.setColor(new Color(64, 64, 64));
          g.fillRect(0, 0, 400, 300);
          g.setColor(Color.YELLOW);
          g.fillOval(x, y, 15, 15);
     }
     @Override
     public void run()
     {
     }
}

救命啊... 写到这儿 卡住了, 脑筋怎么也转不过来,
想实现 运行 就在面板上 出现一个小球 自动移动 遇墙 则换方向,

我现在的问题是, 不知道线程放在哪 
思路应该是   g.fillOval(x, y, 15, 15); 利用repaint();函数重绘 不知道找函数要放到哪去才合适
T.T  x,y 也得放在线程里 , 结果不会取出来 -0 - 悲剧... 想撞墙!....

恳求高手们 指点明路...

------解决方案--------------------
给你参考下,一个用applet写的代码:
最下面那个类是主类,中间是主要;

Ball类:
import javax.swing.Timer;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Ball extends JPanel {
  private int delay = 10;

  // Create a timer with delay 1000 ms
  private Timer timer = new Timer(delay, new TimerListener());

  private int x = 0; private int y = 0; // Current ball position
  private int radius = 5; // Ball radius
  private int dx = 2; // Increment on ball's x-coordinate
  private int dy = 2; // Increment on ball's y-coordinate

  public Ball() {
    timer.start();
  }