2013-11-15 36 views
0
import java.applet.Applet; 
import java.awt.Color; 
import java.awt.Graphics; 

class Ball { 

    int x, y, radius, dx, dy; 
    Color BallColor; 

    public Ball(int x, int y, int radius, int dx, int dy, Color bColor) { 
     this.x = x; 
     this.y = y; 
     this.radius = radius; 
     this.dx = dx; 
     this.dy = dy; 
     BallColor = bColor; 
    } 

} 

public class Bounce extends Applet implements Runnable { 

    Ball redBall; 

    public void init() { 
     redBall = new Ball(250, 80, 50, 2, 4, Color.red); 
     Thread t = new Thread(this); 
     t.start(); 
    } 

    public void paint(Graphics g) { 
     g.setColor(redBall.BallColor); 
     setBackground(Color.pink); 
     g.fillOval(redBall.x, redBall.y, redBall.radius, redBall.radius); 
     g.drawLine(150, 400, 50, 500); 
     g.drawLine(150, 400, 450, 400); 
     g.drawLine(50, 500, 350, 500); 
     g.drawLine(450, 400, 350, 500); 
     g.drawRect(50, 500, 20, 100); 
     g.drawRect(330, 500, 20, 100); 
     g.drawLine(450, 400, 450, 500); 
     g.drawLine(430, 500, 450, 500); 
     g.drawLine(430, 500, 430, 420); 
    } 

    public void run() { 
     while (true) { 
      try { 
       displacementOperation(redBall); 
       Thread.sleep(20); 
       repaint(); 
      } catch (Exception e) { 
      } 
     } 
    } 

    public void displacementOperation(Ball ball) { 
     if (ball.y >= 400 || ball.y <= 0) { 
      ball.dy = -ball.dy; 
     } 
     ball.y = ball.y + ball.dy; 
    } 

} 

當我編譯並運行代碼時說,在Bounce類中找不到主要方法,請將方法定義爲public static void main(String [] args)。我不知道如何解決這個問題,如果有人能指出什麼是錯的,我會很感激。由於在類中找不到的主要方法

+1

你真的有一個主要的方法嗎? – david99world

+0

閱讀「入門」指南(http://docs.oracle.com/javase/tutorial/getStarted/index.html)。你應該知道一個基本的hello世界程序是怎樣的,以及如何在用Java做圖形之前啓動它? –

+1

您正在嘗試從命令行運行Applet。雖然這可以完成,但您需要添加主要方法。小程序不必有主要方法。 – occulus

回答

0

您可以運行在小程序中啓用瀏覽器此applet。該小程序使用以下方法啓動。

public void init() // This method works as like main. 

你只需要在html頁面上配置applet標籤來運行這段代碼。

<applet code = "Bounce.class" 
    width = "500" 
    height = "300"> 
</applet> 
+0

感謝您的好評:) – user81883

相關問題