用以下两个类定义了一个applet:
import javax.swing.JApplet; public class VideoApplet extends JApplet{ public void init() { add(new VideoPanel()); } }
import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class VideoPanel extends JPanel implements ItemListener{ private static final int DEFAULT_WIDTH = 300; private static final int DEFAULT_HEIGHT = 200; private JComboBox<Object> jcb1 = null; private JTextField jtf = null; private double price[] = { 0.0, 2.5, 2.0, 2.0, 2.0 }; private int num = 0; public VideoPanel() { setLayout(new GridLayout(10, 1)); JLabel jl1 = new JLabel("Movie List: "); String videos[] = { "none", "飞屋环游记", "By My Side", "My love", "Apple Dream",}; jcb1 = new JComboBox<Object>(videos); jtf = new JTextField(); jtf.setEditable(false); jtf.setText("Movie Price $" + price[num]); add(jl1); add(jcb1); add(jtf); jcb1.addItemListener(this); } public void itemStateChanged(ItemEvent e) { num = jcb1.getSelectedIndex(); jtf.setText("Movie Price $" + price[num]); } public Dimension getPreferredSize() { return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); } }
还有一个test.html文件,内容如下:
<html> <head> <title>VideoApplet</title> </head> <body> <applet code="VideoApplet.class" width="300" height="300"> </applet> </body> </html>
接下来就是在浏览器中运行applet了。
在浏览器中运行applet需要安装相应的插件,这个只需要按照提示安装就行了。但是,一般情况下,依然不能运行applet,这时就需要把运行applet的网址放进“可运行网址列表”中,操作如下:
进入“控制面板(Control Panel)”,点击“程序(Programs)”,双击“Java”:
在运行出来的“Java控制面板(Java Control Panel)”中选中“安全(Security)”:
点击“编辑网址列表(Edit Site List)”,把要运行applet的网址放进去,结果如下:
然后在浏览器中访问http://localhost:8080/test.html,会有如下提示:
点击“运行(Run)”后,applet便正常运行,结果如下: