建立并运行applet

下面讲解一下如何利用命令行建立并运行applet。然后,利用JDK自带的applet查看器加载applet。
最后,在Web浏览器中显示。

首先,打开shell窗口并将目录转到WelcomeApplet.java和WelcomeApplet.html所在目录,然后,输
入下面命令:
javac WelcomeApplet.java
appletviewer WelcomeApplet.html 

图1显示了在applet查看器窗口中显示的内容。
建立并运行applet
图1
因为配置问题,我这边无法显示在浏览器中运行WelcomeApplet.html,我在网上找了一些解决办法,也做了尝试,还是不能显示出来。如果读者有解决办法请留言。

程序源代码如下:
WelcomeApplet.html如下:
<html>
<head>WelcomeApplet</head>
<body>
<hr/>
<p>
This applet is from the book
<a href="http://ww.horstmann.com/corejava.html">Core Java </a>
by <em>Cay Horstmann</em> and <em>Gary Cornell</em>.
</p>
<applet code="WelcomeApplet.class" width="400" height="200">
<param name="greeting" value="Welcome to Core Java">
</applet>
<hr/>
<p><a href="WelcomeApplet.java">The source.</a></p>
</body>
</html>


WelcomeApplet.java如下:
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.*;


public class WelcomeApplet extends JApplet
{
public void init()
{
setLayout(new BorderLayout());
JLabel label = new JLabel(getParameter("greeting"), SwingConstants.CENTER);
label.setFont(new Font("Serif", Font.BOLD, 18));
add(label, BorderLayout.CENTER);

JPanel panel = new JPanel();

JButton cayButton = new JButton("Cay Horstmann");
cayButton.addActionListener(makeAction("http://www.horstmann.com"));
panel.add(cayButton);

JButton garyButton = new JButton("Gary Cornell");
garyButton.addActionListener(makeAction("mailto:[email protected]"));
panel.add(garyButton);

add(panel, BorderLayout.SOUTH);
}

private ActionListener makeAction(final String urlString)
{
return new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
try
{
getAppletContext().showDocument(new URL(urlString));
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
}
};
}
}