2010-08-06 64 views
0

我剛開始學習揮杆。想到嘗試一個簡單的程序,但我無法運行它。運行一個簡單的揮杆程序時出錯

import java.awt.*; 
import javax.swing.*; 
class MyDrawPanel extends JPanel 
{ 
    public void paintComponent(Graphics g) 
    { 
     g.setColor(Color.orange); 
     g.fillRect(20,50,100,100); 
    } 
} 

我收到以下錯誤:

Exception in thread "main" java.lang.NoSuchMethodError: main 

我的問題:我們必須我們要運行的每個類別的主要方法是什麼? JVM不能運行任何沒有主要方法的類。在這裏,我不需要一個主類,我認爲,cuz這個paintComponent方法應該被系統調用,對吧?

P.S:我使用普通香草cmd進行編譯和運行。

回答

1

java很簡單,當你給它一個類文件時,它會加載它並嘗試執行一個程序。 Java程序被定義爲在「public static void main(String ... args)」方法中開始。所以缺少這個函數的類文件沒有一個程序的有效入口點。

要使java調用paintComponent()方法,必須將類的實例添加到頂層容器(如JFrame)或Web應用程序(JApplet)。 (Applets不使用主要方法,因爲它們是作爲網頁的一部分而不是獨立應用程序執行的。)

實施例:

import javax.swing.* 
public class MyDrawPanel{ 
    public static void main(String... args) 
    { 
     JFrame frame = new JFrame(200,200);//A window with 200x200 pixel 
     MyDrawPanel mdp = new MyDrawPanel();//Panel instance 
     frame.add(mdp);//Add the panel to the window 
     frame.setVisible(true);//Display all 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit when the window is closed 

    } 
} 
0

您需要在該類中運行該程序的主要方法。這是強制性的。如果您有多種方法,JVM如何知道應該調用哪個方法來啓動。他們可以猜測,但大多數時候,猜測可能會出錯。所以,提供一個簡單的主要方法將幫助

1

正如vodkhang所說,你需要一個「主要」方法。確保它看起來就像這樣:

public static void main(String[] args) 
{ 
    // your code here. 
    // this example will use your panel: 

    // create a new MyDrawPanel 
    MyDrawPanel panel = new MyDrawPanel(); 

    // create a frame to put it in 
    JFrame f = new JFrame("Test Frame"); 
    f.getContentPane().add(panel); 

    // make sure closing the frame ends this application 
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    // show the frame 
    f.setSize(100,100); 
    f.setVisible(true); 

} 

是的,您要運行每一個Java程序需要一個main方法正是這個簽名:

public static void main(String[] args) 

您可以從其他系統中運行Java代碼(比如沒有「main」的web服務器等),但只需要運行它,主要是入口點。把它放在你想要啓動程序的地方。

運行時,請確保您的類名稱正確無誤以幫助您找到主要方法。在你的情況,如果你用手在同一個目錄中運行Java作爲你的MyDrawPanel.class文件,你可以這樣做:

java -cp . MyDrawPanel 

如果從一個開發工具中運行,那麼它會提供一種方法來運行你正在看的課程。

1

Do we need to have a main method in every class we want to run?

您需要一個具有主方法的類來啓動JVM。

Can't JVM run any class which doesnt have a main method.

不是最初的。

Here i don't require a main class i think, cuz this paintComponent method should be called by the system, right?

錯誤。確實,最終將由「系統」調用paintComponent()方法,特別是Swing Event Dispatch Thread。但是這需要先開始,當您創建一個窗口並使其可見時,這會隱式發生。而這又只能發生在一個主要的方法。

相關問題