I created the demo below that does the following:
- User writes their class in the
JTextArea
provided. - Clicks on the Instantiate Class
JButton
to create a java file regarding the class created by the user. - Clicks on the Run
JButton
in order to actually use the created class (code commented).
I don't know if this is the best approach (to creat a java file) to run a class created during runtime. However, in my actual project, I do need these created classes in .java files.
I understand that Eclipse does not allow the commented part because at compiling time the compiler has no idea of what myClass
is. How can I do this?
Code:
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(1,3));
JTextArea editor = new JTextArea();
editor.setPreferredSize(new Dimension(400,400));
editor.setTabSize(4);
editor.setText("public class myClass {\n" +
"\tpublic int myValue;\n" +
"\t\n" +
"\tpublic myClass(int value){\n" +
"\t\tmyValue = value;\n" +
"\t}\n" +
"\t\n" +
"\tpublic int getValue() {\n" +
"\treturn myValue;\n" +
"\t}\n" +
"}");
JButton instantiate = new JButton("Instantiate class");
JButton run = new JButton("Run");
frame.getContentPane().add(editor);
frame.getContentPane().add(instantiate);
frame.getContentPane().add(run);
frame.pack();
frame.setVisible(true);
instantiate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
PrintWriter out = new PrintWriter("src/myClass.java");
out.println(editor.getText());
out.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
}
});
run.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//This is what I want to do
//myClass myObject = new myClass(4);
//System.out.println("My value is: " + myObject.getValue());
}
});
}
}