我正在从 Herbert Schildt Book Java2 Complete Reference Fifth Edition 逐步学习 Java。在我通过创建线程并调用 Applet 的 Repaint() 方法来创建简单的横幅 Applet 的过程中,该 Applet 显示横幅并在 Applet 查看器上滚动。但是在创建可运行目标的线程对象时,它会抛出这样的异常
java.security.AccessControlException: access denied (java.lang.RuntimePermission modifyThreadGroup)
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:345)
at java.security.AccessController.checkPermission(AccessController.java:555)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
at sun.applet.AppletSecurity.checkAccess(AppletSecurity.java:252)
at java.lang.ThreadGroup.checkAccess(ThreadGroup.java:304)
at java.lang.ThreadGroup.<init>(ThreadGroup.java:119)
at java.lang.ThreadGroup.<init>(ThreadGroup.java:95)
at Applet.SimpleBanner.start(SimpleBanner.java:49)
at sun.applet.AppletPanel.run(AppletPanel.java:475)
at java.lang.Thread.run(Thread.java:713)
我读了其他文章说它需要安全权限,但在我的 applet.policy 文件中已经允许所有权限
grant { permission java.security.AllPermission;};
这只是我的第二个小程序。谁能用简单的术语详细解释为什么它是 Throwing Security Exception 及其解决方案?
这是我的小程序代码。
import java.applet.Applet;
import java.awt.*;
/* A Simple Banner Applet.
* This Banner Applet Creates a thread that scrolls the message contained
* in msg right to left across banner's window.
*/
/*
* <applet code="SimpleBanner" width=300 height=50>
* </applet>
*/
public class SimpleBanner extends Applet implements Runnable{
private static final long serialVersionUID = 1L;
String msg = "Hello World";
Thread t = null;
ThreadGroup Grp;
int state;
boolean stopflag;
/**
* Initialization method that will be called after the applet is loaded into
* the browser.
*/
@Override
public void init()
{
//Set Foreground and background color
setBackground(Color.cyan);
setForeground(Color.red);
}
@Override
public void start()
{
//Start Thread
Grp = new ThreadGroup("Group");
t = new Thread(Grp, this);
stopflag = false;
t.start();
}
//Entry Point for Thread that Runs The banner
@Override
public void run()
{
char ch;
//Display Banner
for(;;)
{
try {
repaint();
Thread.sleep(250);
ch=msg.charAt(0);
msg =msg.substring(1,msg.length());
msg +=ch;
if (stopflag)
{
break;
}
} catch (InterruptedException ex) {
}
}
}
@Override
public void stop()
{
// Pause The Banner
stopflag=true;
t=null;
}
@Override
public void paint(Graphics g)
{
//Display The Banner
g.drawString(msg, 50, 30);
}
}