【发布时间】:2015-02-22 04:24:25
【问题描述】:
我有一个简单的测试程序,只有一个按钮。当用户单击按钮时,程序应该创建一个 Runnable JAR。 Runnable JAR 是一个在 Firefox 中打开 google.com 的简单程序。该计划分为三个班级。
1) Main.java
package test;
public class Main {
public static void main(String[] args) {
Selenium.getGoogle();
}
}
2) Selenium.Java
package test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Selenium {
public static void getGoogle () {
WebDriver driver = new FirefoxDriver();
driver.get("http://google.com");
}
}
3) TestGUI.java
package test;
import javax.swing.*;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
public TestGUI() {
setSize(200, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
/*
* JButton.
*/
JButton startButton = new JButton("Create Runnable JAR file ! ");
add(startButton);
startButton.addActionListener(this);
}
public static void main(String[] args) {
new TestGUI();
}
public void actionPerformed(ActionEvent e) {
System.out.println("The Button Works");
String file1ToCompile = "test" + java.io.File.separator + "Main.java";
String file2ToCompile = "test" + java.io.File.separator + "Selenium.java";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int compilationResult = compiler.run(null, null, null, file1ToCompile, file2ToCompile);
if (compilationResult == 0) {
System.out.println("Compilation is successful");
} else {
System.out.println("Compilation Failed");
}
}
}
我有两个主要课程。我在清单中添加了TestGUI.java,这样 GUI 就会显示出来。一旦用户单击该按钮,我希望我的程序创建一个包含 Main.java 和 Selenium.java 的可运行 JAR。
但是,对于int compilationResult = compiler.run(null, null, null, file1ToCompile, file2ToCompile);,我收到错误null pointer exception
我该怎么做?
【问题讨论】:
-
然后修正你的标题。它与其他帖子完全相同。
-
如果您粘贴为错误的那行代码是正确的,那么您的
compiler变量看起来是空的。因此,当您尝试在其上调用.run()时,它会引发异常,因为没有人在家。您需要尝试为聚会带来更多东西;您不能真正从互联网上复制/粘贴一些您不理解的代码,然后期望我们向您解释它是如何工作的。 -
“Once”是“ones”的拼写方式。我试图编辑帖子以修复错字,但 SO 不会让我这样做,因为更改是“次要的”。也许在字符中是这样,但是大脑处理意思而不是所说的内容所花费的时间并不是那么小,至少对于患有强迫症的人来说是这样! :)
-
NPE 很可能发生,因为您使用的是 JRE 而不是 JDK,并且
ToolProvider.getSystemJavaCompiler();返回 null 而不是编译器实例。 -
“通过 GUI 以编程方式创建 ...” 不是矛盾吗?