2014-10-31 144 views
0

我正在嘗試使用IntelliJ設置一個簡單的JApplet。我有一個名爲Square的類和一個HTML文件,它應該能夠正常工作,但我一直得到ClassNotFoundExceptionClassNotFound在調用Applet時發生異常

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

public class Square extends JApplet { 

    int size = 40; 

    public void init() { 
     JButton butSmall = new JButton("Small"); 
     JButton butMedium = new JButton("Medium"); 
     JButton butLarge = new JButton("Large"); 
     JButton butMessage = new JButton("Say Hi!"); 

     SquarePanel panel = new SquarePanel(this); 
     JPanel butPanel = new JPanel(); 
     butPanel.add(butSmall); 
     butPanel.add(butMedium); 
     butPanel.add(butLarge); 
     butPanel.add(butMessage); 
     add(butPanel, BorderLayout.NORTH); 
     add(panel, BorderLayout.CENTER); 
    } 
} 

class SquarePanel extends JPanel { 

    Square theApplet; 

    SquarePanel(Square app) { 
     theApplet = app; 
    } 

    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     g.setColor(Color.green); 
     g.fillRect(20, 20, theApplet.size, theApplet.size); 
    } 
} 

和HTML文件

<HTML> 
<APPLET CODE="Square.class"> WIDTH=400 HEIGHT=200> 
</APPLET> 
</HTML> 

這是文件夾結構。我嘗試了很多不同的組合和名稱,並嘗試了很多分隔符,但我無法正確打開它。

folder image

回答

2

的問題是,小應用程序容器,通常是瀏覽器,被告知在哪裏可以找到類Square而不是類SquarePanel。你可以做任何的兩件事情:

  • 附上你的類的JAR和您的<APPLET\>標籤指定archive名,如here

  • Nest SquarePanel in Square,如下所示用於說明目的。

JAR是首選方法,但也考慮使用hybrid進行更靈活的測試和部署。爲了方便appletviewer測試,標籤包含在註釋中,如here所示。

image

命令行:

$ appletviewer Square.java 

代碼,測試:

// <applet code='Square' width='400' height='200'></applet> 
import javax.swing.*; 
import java.awt.*; 

public class Square extends JApplet { 

    int size = 40; 

    public void init() { 
     JButton butSmall = new JButton("Small"); 
     JButton butMedium = new JButton("Medium"); 
     JButton butLarge = new JButton("Large"); 
     JButton butMessage = new JButton("Say Hi!"); 

     SquarePanel panel = new SquarePanel(this); 
     JPanel butPanel = new JPanel(); 
     butPanel.add(butSmall); 
     butPanel.add(butMedium); 
     butPanel.add(butLarge); 
     butPanel.add(butMessage); 
     add(butPanel, BorderLayout.NORTH); 
     add(panel, BorderLayout.CENTER); 
    } 

    private static class SquarePanel extends JPanel { 

     Square theApplet; 

     SquarePanel(Square app) { 
      theApplet = app; 
     } 

     public void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      g.setColor(Color.green); 
      g.fillRect(20, 20, theApplet.size, theApplet.size); 
     } 
    } 
} 
+0

參見[*爲什麼CS教師應停止教學Java小程序*](HTTP://程序員.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets /)和[*初始線程*](http://docs.oracle.com/javase/tutorial/uiswing/併發/ initial.html)。 – trashgod 2014-10-31 17:43:37

相關問題