在此applet中将类声明为public是什么?

时间:2011-10-21 09:30:46

标签: java applet

CODE

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

/* <applet code="tester" height=400 width=400>
 * </applet>
 */

class tester extends JApplet {

boolean isFirst = true;

public void init() {

}

public void start() {
addMouseMotionListener(new MouseMotionAdapter() {
    @Override
      public void mouseMoved(MouseEvent evt) {
        half_tester(evt);
      }
});
}

public void paint(Graphics g) {
  if(isFirst) {
//JOptionPane.showMessageDialog(new JFrame(),"first time");
System.out.println("first time");
isFirst = false;
   } else {
 //JOptionPane.showMessageDialog(new JFrame(),"not the first time");
  System.out.println("not the first time!");
     }
}

public void half_tester(MouseEvent evt) {
   repaint();
}
}

例外

load: tester is not public or has no public constructor.
java.lang.IllegalAccessException: Class sun.applet.AppletPanel can not access a member of class tester with modifiers ""
    at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:95)
    at java.lang.Class.newInstance0(Class.java:366)
    at java.lang.Class.newInstance(Class.java:325)
    at sun.applet.AppletPanel.createApplet(AppletPanel.java:795)
    at sun.applet.AppletPanel.runLoader(AppletPanel.java:724)
    at sun.applet.AppletPanel.run(AppletPanel.java:378)
    at java.lang.Thread.run(Thread.java:729)

为什么我需要声明公开课?

1 个答案:

答案 0 :(得分:2)

  

为什么我需要声明公开课?

因为其他包(例如sun.applet.AppletPanel)的其他类无法访问它。

如果你没有在你的类定义中添加public,那么它只能看到它的包,它是你案例中的默认包。