-2

Java プログラムをアプレット ウィンドウまたは Swing ウィンドウで実行できますか? また、コンパイルされたプログラムの出力を確認するにはどうすればよいですか?

4

4 に答える 4

3

コンパイラ API (Java 6 で使用可能) を使用してソースをコンパイルできます。

新しいプロセス (main() エントリがある場合) ポイントを exec() するか、クラスローディングを使用して JVM にロードすることができます。後者のコースを受講する場合は、毎回新しいクラスローダーをインスタンス化する必要がある可能性が高いことに注意してください。詳細については、こちらを参照してください。

セキュリティ上の懸念があるかもしれません。アプレットからファイル システムにアクセスします。そのため、標準の Swing アプリケーション (おそらく Java Web Start を使用してロードされますか?) を使用する方がよい場合があります。

于 2012-10-18T10:06:22.957 に答える
2

再。JavaCompiler API とアプレットまたは Swing が JWS で起動されました。

テキスト領域で、またはコードベースからの URL で提供されたソースをコンパイルするには、信頼は必要ありません。OTOH はJavaCompiler、コードが JDK の JVM で実行されている場合にのみ使用できます (tools.jar実行時のクラスパスにある必要があります)。アプレットと JWS ベースのアプリ。JDK を使用して実行されることはなく、使用可能になることもありませtools.jarん。

こちらもご覧ください

サンプルコード

「リンクの腐敗」を避けるために、リンクされたスレッドで見られるコードを次に示します。

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.EventQueue;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
 
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.SwingWorker;
import javax.swing.border.EmptyBorder;
 
import java.util.ArrayList;
 
import java.net.URI;
 
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
 
import javax.tools.ToolProvider;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
 
/** A simple Java compiler with a GUI.  Java 1.6+.
@author Andrew Thompson
@version 2008-06-13
*/
public class GuiCompiler extends JPanel {
 
  /** Instance of the compiler used for all compilations. */
  JavaCompiler compiler;
 
  /** The name of the public class.  For 'HelloWorld.java',
  this would be 'HelloWorld'. */
  JTextField name;
  /** The source code to be compiled. */
  JTextArea sourceCode;
  /** Errors and messages from the compiler. */
  JTextArea output;
 
  JButton compile;
 
  static int pad = 5;
 
  GuiCompiler() {
    super( new BorderLayout(pad,pad) );
    setBorder( new EmptyBorder(7,4,7,4) );
  }
 
  /** A worker to perform each compilation. Disables
  the GUI input elements during the work. */
  class SourceCompilation extends SwingWorker<String, Object> {
    @Override
    public String doInBackground() {
      return compileCode();
    }
 
    @Override
    protected void done() {
      try {
        enableComponents(true);
      } catch (Exception ignore) {
      }
    }
  }
 
  /** Construct the GUI. */
  public void initGui() {
    JPanel input = new JPanel( new BorderLayout(pad,pad) );
    Font outputFont = new Font("Monospaced",Font.PLAIN,12);
 
    sourceCode = new JTextArea("Paste code here..", 15, 60);
    sourceCode.setFont( outputFont );
    input.add( new JScrollPane( sourceCode ),
      BorderLayout.CENTER );
    sourceCode.select(0,sourceCode.getText().length());
 
    JPanel namePanel = new JPanel(new BorderLayout(pad,pad));
    name = new JTextField(15);
    name.setToolTipText("Name of the public class");
    namePanel.add( name, BorderLayout.CENTER );
    namePanel.add( new JLabel("Class name"), BorderLayout.WEST );
 
    input.add( namePanel, BorderLayout.NORTH );
 
    compile = new JButton( "Compile" );
    compile.addActionListener( new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          (new SourceCompilation()).execute();
        }
      } );
    input.add( compile, BorderLayout.SOUTH );
 
    this.add( input, BorderLayout.CENTER );
 
    output = new JTextArea("", 5, 40);
    output.setFont( outputFont );
    output.setEditable(false);
    this.add( new JScrollPane( output ), BorderLayout.SOUTH );
  }
 
  /** Compile the code in the source input area. */
  public String compileCode() {
    output.setText( "Compiling.." );
    enableComponents(false);
    String compResult = null;
    if (compiler==null) {
      compiler = ToolProvider.getSystemJavaCompiler();
    }
    if ( compiler!=null ) {
      String code = sourceCode.getText();
      String sourceName = name.getText().trim();
      if ( sourceName.toLowerCase().endsWith(".java") ) {
        sourceName = sourceName.substring(
          0,sourceName.length()-5 );
      }
      JavaSourceFromString javaString = new JavaSourceFromString(
        sourceName,
        code);
      ArrayList<JavaSourceFromString> al =
        new ArrayList<JavaSourceFromString>();
      al.add( javaString );
 
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      OutputStreamWriter osw = new OutputStreamWriter( baos );
 
      JavaCompiler.CompilationTask task = compiler.getTask(
        osw,
        null,
        null,
        null,
        null,
        al);
 
      boolean success = task.call();
 
      output.setText( baos.toString().replaceAll("\t", "  ") );
      compResult = "Compiled without errors: " + success;
      output.append( compResult );
      output.setCaretPosition(0);
    } else {
      output.setText( "No compilation possible - sorry!" );
      JOptionPane.showMessageDialog(this,
        "No compiler is available to this runtime!",
        "Compiler not found",
        JOptionPane.ERROR_MESSAGE
        );
      System.exit(-1);
    }
    return compResult;
  }
 
  /** Set the main GUI input components enabled
  according to the enable flag. */
  public void enableComponents(boolean enable) {
    compile.setEnabled(enable);
    name.setEnabled(enable);
    sourceCode.setEnabled(enable);
  }
 
  public static void main(String[] args) throws Exception {
 
    Runnable r = new Runnable() {
      public void run() {
        JFrame f = new JFrame("SSCCE text based compiler");
        f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
 
        GuiCompiler compilerPane = new GuiCompiler();
        compilerPane.initGui();
 
        f.getContentPane().add(compilerPane);
 
        f.pack();
        f.setMinimumSize( f.getSize() );
        f.setLocationRelativeTo(null);
        f.setVisible(true);
      }
    };
    EventQueue.invokeLater(r);
  }
}
 
/**
* A file object used to represent source coming from a string.
* This example is from the JavaDocs for JavaCompiler.
*/
class JavaSourceFromString extends SimpleJavaFileObject {
  /**
  * The source code of this "file".
  */
  final String code;
 
  /**
  * Constructs a new JavaSourceFromString.
  * @param name the name of the compilation unit represented
    by this file object
  * @param code the source code for the compilation unit
    represented by this file object
  */
  JavaSourceFromString(String name, String code) {
    super(URI.create(
      "string:///" +
      name.replace('.','/') +
      Kind.SOURCE.extension),
      Kind.SOURCE);
    this.code = code;
  }
 
  @Override
  public CharSequence getCharContent(boolean ignoreEncodingErrors) {
    return code;
  }
}
于 2012-10-18T11:03:30.613 に答える
0

アプレットはバックグラウンドで実行されるプログラムです.Javaプログラムをコンパイルするには、IS NOT ALLOWEDセキュリティ上の理由から、アプレット用のクライアントのローカルディスクにアクセスする必要があります(私の知る限り)。何を達成しようとしていますか?アプレットを使用して img ファイルにアクセスしようとしたことがあります。

于 2012-10-18T10:12:27.283 に答える
0

Java Compiler APIを使用して、ソース コードをバイトコードに変換します。その後、動的クラスローディングを使用して、コンパイルされたバイトコードを jvm にロードし、起動します (出力を取得するため)。
また、Java アプレットの内部からこれを行う場合は、セキュリティの問題を解決する必要があります。

于 2012-10-18T10:11:09.767 に答える