コード例 #1
0
ファイル: JavaCompile.java プロジェクト: shamim8888/scalalab
  // compile a Java file with the installed javac compiler
  public boolean compileFile(String sourceFile) {
    boolean compilationResult = true; // no errors

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) { // Sterg-SOS why not loaded?
      System.out.println(
          "ToolProvider.getSystemJavaCompiler: no compiler provided. Unable to compile");
    }
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);

    StringWriter compileWriter = new StringWriter();

    List<File> sourceFileList = new ArrayList<File>();
    sourceFileList.add(new File(sourceFile));
    Iterable<? extends JavaFileObject> compilationUnits =
        fileManager.getJavaFileObjectsFromFiles(sourceFileList);

    String pathOfFile = sourceFile.substring(0, sourceFile.lastIndexOf(File.separatorChar));
    String classpath =
        GlobalValues.jarFilePath
            + File.pathSeparatorChar
            + pathOfFile
            + File.pathSeparatorChar
            + ".";
    Iterable<String> options = Arrays.asList("-cp", classpath);

    CompilationTask task =
        compiler.getTask(compileWriter, fileManager, null, options, null, compilationUnits);

    boolean compileResult = task.call();
    if (compileResult == false) {
      compilationResult = false; // compilation errors
      JFrame compResultsFrame = new JFrame("Compilation Results");
      String diagnString = compileWriter.toString();
      JTextArea compResultsArea = new JTextArea(diagnString);
      compResultsArea.setFont(new Font("Arial", Font.BOLD, 16));
      JPanel compResultsPanel = new JPanel();
      compResultsPanel.add(compResultsArea);
      compResultsFrame.add(compResultsPanel);
      compResultsFrame.setSize(800, 200);
      compResultsFrame.setLocation(100, 200);
      compResultsFrame.setVisible(true);
      int response =
          JOptionPane.showOptionDialog(
              null,
              "File " + sourceFile + " has compilation errors ",
              "Edit File? ",
              JOptionPane.YES_NO_OPTION,
              JOptionPane.QUESTION_MESSAGE,
              null,
              null,
              null);
      if (response == JOptionPane.YES_OPTION) { // edit it with scalalabEditor
        new scalalabEdit.EditorPaneEdit(sourceFile);
      }
    }

    try {
      fileManager.close();
    } catch (IOException e) {
    }

    return compilationResult;
  }