I have a code that compiles a java source file and runs it . the console output is displayed in a jtextarea in the application. the problem is although , the source file is being compiled and the .class files are being created , the output jtextarea does not displays anything . i tried running the lengthy tasks on a different thread , but that doesnt helps either. what am i doing wrong here ?
UPDATE: i updated the write method of my custom output stream class to include the append method in a swing worker class.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
class test extends JFrame
{
JTextArea content,compiler;
JSplitPane pane;
JMenuBar jmb = new JMenuBar();
JMenu menu = new JMenu("Options");
JMenuItem item = new JMenuItem("Compile") , item1 = new JMenuItem("Run") , item2 = new JMenuItem("Save");
test()
{
setTitle("Testing Window");
setSize(700,700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
content = new JTextArea();
compiler = new JTextArea();
PrintStream stream = new PrintStream(new cos(compiler));
System.setOut(stream);
System.setErr(stream);
pane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,true,new JScrollPane(content),new JScrollPane(compiler));
pane.setResizeWeight(0.8);
add(pane);
menu.add(item);
menu.add(item1);
menu.add(item2);
jmb.add(menu);
setJMenuBar(jmb);
ActionListener listener = (ActionEvent ae) -> {
try(FileWriter file = new FileWriter("hello.java");
BufferedWriter bw = new BufferedWriter(file))
{
Scanner sc = new Scanner(content.getText());
while( sc.hasNext())
{
bw.write(sc.nextLine());
bw.newLine();
}
}catch(Exception e){e.printStackTrace();}
};
item2.addActionListener(listener);
ActionListener listener1 = (ActionEvent ae)->{
Runnable runnable = ()->{
try
{
Process p = Runtime.getRuntime().exec("javac hello.java");
p.waitFor();
System.out.print("Compiled Successfully \n");
}catch(Exception e){e.printStackTrace();}
};
Thread newThread = new Thread(runnable);
newThread.start();
};
item.addActionListener(listener1);
ActionListener listener2 = (ActionEvent ae)->{
Runnable runnable = ()->{
try
{
Process p = Runtime.getRuntime().exec("java hello");
p.waitFor();
}catch(Exception e){e.printStackTrace();}
};
Thread newThread = new Thread(runnable);
newThread.start();
};
item1.addActionListener(listener2);
setVisible(true);
}
public static void main(String args[])
{
SwingUtilities.invokeLater( ()->{new test();} );
}
}
class cos extends OutputStream
{
JTextArea textarea;
SwingWorker worker;
cos(JTextArea textarea)
{
this.textarea = textarea;
}
public void write(int b)throws IOException
{
worker = new SwingWorker()
{
protected Object doInBackground()
{
publish(String.valueOf( (char)b ));
return null;
}
protected void process(ArrayList<String> list)
{
textarea.append(list.get(list.size()-1))//to get latest string
}
};
worker.execute();
}
}