import java.awt.BorderLayout;import java.awt.EventQueue;import java.awt.Font;import java.awt.Graphics;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.net.URL;import javax.swing.JApplet;import javax.swing.JButton;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.SwingConstants;public class WelcomeApplet extends JApplet { private static final long serialVersionUID = 1L; public void init() { EventQueue.invokeLater(new Runnable() { @Override public void run() { setLayout(new BorderLayout()); JLabel label = new JLabel("Hello "+getParameter("greeting"), SwingConstants.CENTER); label.setFont(new Font("Serif", Font.BOLD, 18)); add(label, BorderLayout.CENTER); JPanel panel = new JPanel(); JButton cayButton = new JButton("cnblogs"); cayButton.addActionListener(makeAction("http://www.cnblogs.com")); panel.add(cayButton); add(panel, BorderLayout.SOUTH); } private ActionListener makeAction(final String string) { return new ActionListener() { public void actionPerformed(ActionEvent event) { try { getAppletContext().showDocument(new URL(string)); } catch (Exception e) { e.printStackTrace(); } } }; } }); }}
以上的java代码编译成class文件之后,新建一个index.html,内容如下:
一个带有传参,按钮的applet小程序就可以在网页上运行了,显示效果如下:
参考文献: 《Core Java 卷1》 第二章