applet示例 WelcomeApplet.java

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,内容如下:

<html>
<body>
<applet code="WelcomeApplet.class" width="200" height="200" >
<param name="greeting" value="applet"/>
</applet>
</body>
</html>

一个带有传参,按钮的applet小程序就可以在网页上运行了,显示效果如下:

applet示例 WelcomeApplet.java <Core Java>

参考文献:  《Core Java 卷1》 第二章

上一篇:an interview question(1)


下一篇:Core Java Volume I — 4.7. Packages