Java 教程适用于 JDK 8。本页中描述的示例和实践不利用后续版本引入的改进,并且可能使用不再可用的技术。
有关 Java SE 9 及后续版本中更新的语言特性的摘要,请参阅 Java 语言更改。
有关所有 JDK 版本的新功能、增强功能以及已删除或不推荐使用的选项的信息,请参阅 JDK 发布说明。
参数对于Java小程序来说,就像命令行参数对于应用程序一样。它们使用户能够自定义小程序的操作。通过定义参数,您可以增加小程序的灵活性,使小程序能在多种情况下工作,而无需重新编码和重新编译。
您可以在小程序的Java网络启动协议(JNLP)文件或<applet>标签的<parameter>元素中指定小程序的输入参数。通常最好在小程序的JNLP文件中指定参数,这样即使小程序部署在多个网页上,参数也可以保持一致。如果小程序的参数会因网页而异,则应在<applet>标签的<parameter>元素中指定参数。
如果您对JNLP不熟悉,请参阅Java网络启动协议主题获取更多信息。
考虑一个接受三个参数的小程序。在小程序的JNLP文件中指定了applettakesparams.jnlpparamStr和paramInt参数。
<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="1.0+" codebase="" href="">
<!-- ... -->
<applet-desc
name="Applet Takes Params"
main-class="AppletTakesParams"
width="800"
height="50">
<param name="paramStr"
value="someString"/>
<param name="paramInt" value="22"/>
</applet-desc>
<!-- ... -->
</jnlp>
在中的部署工具脚本的AppletPage.htmlrunApplet函数中的parameters变量中指定了paramOutsideJNLPFile参数。
<html>
<head>
<title>Applet Takes Params</title>
<meta http-equiv="Content-Type" content="text/html;
charset=windows-1252">
</head>
<body>
<h1>Applet Takes Params</h1>
<script
src="https://www.java.com/js/deployJava.js"></script>
<script>
var attributes = { code:'AppletTakesParams.class',
archive:'applet_AppletWithParameters.jar',
width:800, height:50 };
var parameters = {jnlp_href: 'applettakesparams.jnlp',
paramOutsideJNLPFile: 'fooOutsideJNLP' };
deployJava.runApplet(attributes, parameters, '1.7');
</script>
</body>
</html>
请查看部署Applet了解有关runApplet函数的更多信息。
您可以使用Applet类的getParameter方法来检索Applet的输入参数。 Applet检索并显示其所有输入参数(AppletTakesParams.javaparamStr,paramInt和paramOutsideJNLPFile)。
import javax.swing.JApplet;
import javax.swing.SwingUtilities;
import javax.swing.JLabel;
public class AppletTakesParams extends JApplet {
public void init() {
final String inputStr = getParameter("paramStr");
final int inputInt = Integer.parseInt(getParameter("paramInt"));
final String inputOutsideJNLPFile = getParameter("paramOutsideJNLPFile");
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI(inputStr, inputInt, inputOutsideJNLPFile);
}
});
} catch (Exception e) {
System.err.println("createGUI未能成功完成");
}
}
private void createGUI(String inputStr, int inputInt, String inputOutsideJNLPFile) {
String text = "Applet的参数是 - inputStr:" + inputStr +
",inputInt:" + inputInt +
",paramOutsideJNLPFile:" + inputOutsideJNLPFile;
JLabel lbl = new JLabel(text);
add(lbl);
}
}
接下来显示AppletTakesParams Applet。