SwingWorker with FileReader - java

I have problem about applied SwingWorker with FileReader and my point is I need to implement FileReader with SwingWorker to make my UI Show the text from the file and this is my code
class Read1 extends SwingWorker<String,String>{
protected Void doInBackground() throws Exception{
FileReader read = new FileReader("msg.txt");
BufferedReader in = new BufferedReader(read);
String s;
s=in.readLine();
System.out.println(s);
return s;
}
protected void done()
{
try{
String show;
show=get();
textArea.append(show);}catch(Exception e){}}
public static void main(String args[]) {
Read1 r = new Form().new Read1();
r.execute();
However it does not append anything on the UI textarea
anyone have solution? Thank you

Works just fine for me:
public class Reader extends SwingWorker<List<String>, String> {
protected List<String> doInBackground() throws Exception {
ArrayList<String> lstText = new ArrayList<String>(25);
BufferedReader in = null;
try {
FileReader read = new FileReader("Scanner.txt");
in = new BufferedReader(read);
String s = null;
while ((s = in.readLine()) != null) {
lstText.add(s);
publish(s);
}
} finally {
try {
in.close();
} catch (Exception e) {
}
}
return lstText;
}
#Override
protected void process(List<String> chunks) {
for (String text : chunks) {
fldText.append(text + "\n");
}
}
#Override
protected void done() {
}
}

Related

Java System.out not Being Redirected

I have a simple task of capturing all System.out output; I am however failing:
public class Main {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
ArrayList<String> history = new ArrayList<>();
StringBuilder output = new StringBuilder();
StringBuilder input = new StringBuilder();
JPanel panel = new JPanel();
JTextArea txt = new JTextArea();
String PROMPT = "> ";
Runnable show = new Runnable() {
public void run() {
txt.setText("");
for (String line: history) txt.append(line + "\n");
txt.append(PROMPT);
txt.append(output.toString());
txt.setCaretPosition(txt.getText().length());
}
};
PrintStream os = new PrintStream(new OutputStream() {
#Override
public void write(int b) throws IOException {
if (b == 13) {
history.add(input.toString());
input = new StringBuilder();
SwingUtilities.invokeLater(show);
} else input.append((char)b);
}
});
void init(String title) {
panel.setLayout(new BorderLayout());
txt.setLineWrap(true);
txt.setFont(new Font("Courier", Font.PLAIN, 16));
txt.setBackground(Color.BLACK);
txt.setForeground(Color.GREEN);
txt.setCaretColor(Color.GREEN);
txt.setEditable(false);
txt.setText(PROMPT);
txt.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == '\n') {
System.setOut(os);
System.setErr(os);
String result = output.toString();
history.add(PROMPT + result);
try {
engine.eval(result);
} catch (ScriptException ex) {
history.add(ex.toString());
}
output = new StringBuilder();
} else {
output.append(e.getKeyChar());
}
SwingUtilities.invokeLater(show);
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
});
panel.add(txt, BorderLayout.CENTER);
JFrame frame = new JFrame(title);
frame.setSize(650, 425);
frame.setContentPane(panel);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String args[]) {
new Main().init("javascript");
}
}
I should note the output I am looking for comes from something like:
new ScriptEngineManager().getEngineByName("js").eval("print(\"test\");");
The output is not going anywhere other than normal STDOUT a.k.a. System.out. Why?
ScriptEngine output redirection:
To redirect the output of a script you first have to get its ScriptContext instance, that has a method called setWriter(Writer).
That sets the output of the ScriptEngine.
For that you first need a Writer. This can be simple like this one:
public class CaptureWriter extends Writer
{
private StringBuilder m_build;
public CaptureWriter(StringBuilder build)
{
m_build = build;
}
#Override
public void write(char[] cbuf, int off, int len) throws IOException
{
m_build.insert(m_build.length(), cbuf, off, len);
}
#Override
public void flush() throws IOException
{
}
#Override
public void close() throws IOException
{
}
}
This writes all input into a StringBuilder.
Then you register it into a ScriptContext
ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
engine.getContext().setWriter(new CaptureWriter(m_mess));
When running this simple program:
StringBuilder build = new StringBuilder();
ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
engine.getContext().setWriter(new CaptureWriter(build));
try
{
engine.eval("print(\"Hello\")");
engine.eval("print(\"World\")");
engine.eval("print(\"You\")");
engine.eval("print(\"There\")");
} catch(ScriptException e)
{
e.printStackTrace();
}
System.out.println(build);
The output is the buffered output of the script:
Hello
World
You
There
You can of course hook anything into the write method of the Writer implementation, this is just an example.
System.out redirection:
To capture the System.out output you have to make your own PrintStream implementation, it can be very simple like:
public class Capture extends PrintStream
{
private StringBuilder m_build;
public Capture(OutputStream out, StringBuilder build)
{
super(out);
m_build = build;
}
public void println(String s)
{
super.println(s);
m_build.append(s + "\n");
}
}
Then you need to register it in the runtime:
StringBuilder build = new StringBuilder();
System.setOut(new Capture(System.out, build));
Then every time System.out.println is called it works like the overriding PrintStream should and the message gets written into the provided StringBuilder.
To capture other messages you'll need to override other methods.
You can capture System.out be providing a PrintStream that you control ... try something like this
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
PrintStream old = System.out;
System.setOut(ps);
System.out.println("This will be captured :P");
System.out.flush();
System.setOut(old);
System.out.println("He is what was captured : " + baos.toString());

Exception thrown from the UncaughtExceptionHandler

I am writing an apk analysis program. I cannot go deep into details because it's research material. However, the point is that from time to time when I execute the analysis routine, I get the following message:
Exception: java.lang.NullPointerException thrown from the UncaughtExceptionHandler in thread "main"
This happens if I do not override the UncaughtExceptionHandler and also if I do, as you'll see from the code below. Since there is no stacktrace data I cannot know where that exception is coming from and what its cause really is.
I hope you can help me...
This is only the main code. There are three main operation that I have to execute. In order not to disclose particular information, I renamed them to A, B and C
public class MainScannerSequential {
public static void main(String[] args) throws ParserConfigurationException, IOException, InterruptedException {
final File target = new File(args[1]);
final File result = new File(args[2]);
final Options options = new Options(args);
silentMode = options.contains("-s");
noA = options.contains("-nl");
noC = options.contains("-ne");
aStrategy = Factory.createA();
bScanner = Factory.createB();
cDetector = Factory.createcC();
examinedFiles = new PersistentFileList(Globals.EXAMINED_FILES_LIST_FILE);
if (result.exists())
resultsWriter = new BufferedWriter(new FileWriter(result, true));
else {
resultsWriter = new BufferedWriter(new FileWriter(result));
resultsWriter.write("***");
resultsWriter.newLine();
}
if (Globals.PERFORMANCE_FILE.exists())
performancesWriter = new BufferedWriter(new FileWriter(Globals.PERFORMANCE_FILE, true));
else {
performancesWriter = new BufferedWriter(new FileWriter(Globals.PERFORMANCE_FILE));
performancesWriter.write("***");
performancesWriter.newLine();
}
Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread t, Throwable e) {
if ((t != null) && (t.getName() != null))
System.out.println("In thread : " + t.getName());
if ((e != null) && (e.getMessage() != null)) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
if (e.getStackTrace() != null)
for (StackTraceElement ste : e.getStackTrace())
if (ste != null)
System.out.println(ste.getFileName() + " at line " + ste.getLineNumber());
}
}
});
if (target.isDirectory()) {
enumerateDirectory(target);
} else {
String name = target.getName().toLowerCase();
if (name.endsWith(".apklist"))
readFileList(target);
else if (name.endsWith(".apk"))
checkFile(target);
}
closeWriters();
}
private static void println(String message) {
if (!silentMode)
System.out.println(message);
}
private static void print(String message) {
if (!silentMode)
System.out.print(message);
}
private static void enumerateDirectory(File directory) {
for (File file : directory.listFiles()) {
checkFile(file);
if (file.isDirectory())
enumerateDirectory(file);
}
}
private static void readFileList(File file) {
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
while((line = reader.readLine()) != null) {
File readFile = new File(line);
if (readFile.exists())
checkFile(readFile);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void checkFile(File file) {
if (examinedFiles.contains(file)) {
println("Skipped: " + file.getName());
return;
}
if (!file.getName().toLowerCase().endsWith(".apk")) {
return;
}
final Wrapper<Double> unpackingTime = new Wrapper<Double>(0.0);
final ApplicationData data = unpack(file, unpackingTime);
if (data == null) {
return;
}
scanData(data, unpackingTime.value);
}
private static ApplicationData unpack(final File file, final Wrapper<Double> unpackingTime) {
final Wrapper<ApplicationData> resultWrapper = new Wrapper<ApplicationData>(null);
final Wrapper<Exception> exceptionWrapper = new Wrapper<Exception>(null);
println("Unpacking: " + file.getName());
unpackingTime.value = Stopwatch.time(new Runnable() {
#Override
public void run() {
try {
resultWrapper.value = ApplicationData.open(file);
} catch (Exception e) {
exceptionWrapper.value = e;
}
}
});
if (resultWrapper.value != null)
println("Unpacked: " + file.getName());
else if (exceptionWrapper.value != null)
println("Dropped: " + file.getName() + " : " + exceptionWrapper.value.getMessage());
return resultWrapper.value;
}
private static void scanData(final ApplicationData applicationData, Double unpackingTime) {
String apkName = applicationData.getDecodedPackage().getOriginalApk().getAbsolutePath();
println("Submitted: " + apkName);
examinedFiles.add(applicationData.getDecodedPackage().getOriginalApk());
final Wrapper<Boolean> aDetected = new Wrapper<Boolean>(false);
final Wrapper<Result> bDetected = new Wrapper<Result>(new Result());
final Wrapper<Boolean> cDetected = new Wrapper<Boolean>(false);
final Wrapper<Double> aDetectionTime = new Wrapper<Double>((double)ANALYSIS_TIMEOUT);
final Wrapper<Double> bDetectionTime = new Wrapper<Double>((double)ANALYSIS_TIMEOUT);
final Wrapper<Double> cDetectionTime = new Wrapper<Double>((double)ANALYSIS_TIMEOUT);
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(new Runnable() {
#Override
public void run() {
textDetectionTime.value = Stopwatch.time(new Runnable() {
#Override
public void run() {
bScanner.setUnpackedApkDirectory(applicationData.getDecodedPackage().getDecodedDirectory());
bDetected.value = bScanner.evaluate();
}
});
}
});
if (!noA)
executor.submit(new Runnable() {
#Override
public void run() {
lockDetectionTime.value = Stopwatch.time(new Runnable() {
#Override
public void run() {
aStrategy.setTarget(applicationData.getDecodedPackage());
aDetected.value = aStrategy.detect();
}
});
}
});
if (!noC)
executor.submit(new Runnable() {
#Override
public void run() {
encryptionDetectionTime.value = Stopwatch.time(new Runnable() {
#Override
public void run() {
cDetector.setTarget(applicationData.getDecodedPackage());
cDetected.value = cDetector.detect();
}
});
}
});
boolean timedOut = false;
executor.shutdown();
try {
if (!executor.awaitTermination(ANALYSIS_TIMEOUT, TimeUnit.SECONDS)) {
executor.shutdownNow();
timedOut = true;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
resultsWriter.write(String.format("%s, %b, %b, %f, %b, \"%s\", %b\n",
apkName,
aDetected.value,
bDetected.value.isAccepted(),
bDetected.value.getScore(),
cDetected.value,
bDetected.value.getComment(),
timedOut));
performancesWriter.write(String.format("%s, %f, %f, %f, %f, %d, %dl, %dl\n",
apkName,
aDetectionTime.value,
bDetectionTime.value,
cDetectionTime.value,
unpackingTime,
applicationData.getSmaliLoader().getClassesCount(),
applicationData.getSmaliLoader().getTotalClassesSize(),
applicationData.getDecodedPackage().getOriginalApk().length()));
resultsWriter.flush();
performancesWriter.flush();
} catch (IOException e) { }
// No longer deleting temp files
if (!timedOut)
println("Completed: " + apkName);
else {
print("Timeout");
if (bDetectionTime.value == 0) print(" TextDetection");
if (!noA && (aDetectionTime.value == 0)) print(" LockDetection");
if (!noC && (cDetectionTime.value == 0)) print(" EncryptionDetection");
println(": " + apkName);
}
}
private static void closeWriters() throws IOException {
resultsWriter.close();
performancesWriter.close();
examinedFiles.dispose();
}
private static final int ANALYSIS_TIMEOUT = 40; // seconds
private static Boolean silentMode = false;
private static Boolean noA = false;
private static Boolean noC = false;
private static PersistentFileList examinedFiles;
private static BufferedWriter resultsWriter;
private static BufferedWriter performancesWriter;
private static A aStrategy;
private static B bScanner;
private static C cDetector;
}
I labeled the question as multithread because the same happens in the multithreaded version, which I serialized using this code in order to debug that error. Notice that the NullPointerException is in thread main, not in other Executor-spawned threads.
If you don't have a stack trace, it could mean that there are some crazy exceptions thrown in your code (see Exception without stack trace in Java), but it is more likely that the JVM is re-using exception objects as a performance optimization and the -XX:-OmitStackTraceInFastThrow JVM option would help you.
See this article for details

JavaFX ReadFile counter + another counter task?

i have a UI whit 2 labels.
First Label: All Lines
Second Label: Lines ends with xxx
My Programm Read a File and in a Task he Read all Lines:
public class ReadFileTask extends Task<Void> {
#Override
protected Void call() throws Exception {
File file = new File("comments.txt"); //TODO
long lines = Files.lines(file.toPath()).count();
long line = 0;
BufferedReader reader = new BufferedReader(new FileReader(file));
while ((reader.readLine()) != null) {
line++;
updateMessage("" + line);
}
return null;
}}
Now i have the First label.
For the 2nd Label i try this:
public class ReadFileTask extends Task<Void> {
static int xxxLines = 0;
#Override
protected Void call() throws Exception {
File file = new File("comments.txt"); //TODO
long lines = Files.lines(file.toPath()).count();
long line = 0;
BufferedReader reader = new BufferedReader(new FileReader(file));
while ((reader.readLine()) != null) {
line++;
updateMessage("" + line);
if (reader.readLine().endsWith("xxx")) {
xxxLines++;
}
}
return null;
}}
the Button is:
public void Datei(ActionEvent event) throws IOException, InterruptedException {
ReadFileTask task = new ReadFileTask();
daten.textProperty().bind(task.messageProperty());
new Thread(task).start();
Platform.runLater(()->xxx.setText("" + ReadFileTask.xxxLines));
}
Use Platform.runLater() for your second Label. But beware: Do not flood the GUI Thread with these updates:
Platform.runLater(()->xxxLabel.setText("" + xxxLines));

JavaFX : Redirect Input/Output/Error From ProcessBuilder to TextArea?

I am learning JavaFX and experimenting with it. I tried to build a Console/Command Prompt . But i don't know how to redirect Input/Output/Error From ProcessBuilder to TextArea.
Code:
public class JavaFXConsole extends Application {
ProcessBuilder pb;
Process process;
TextArea ta;
String input = "";
int counter = 0;
//static BufferedReader stdInput, stdError;
//static Thread outputThread;
#Override
public void start(Stage primaryStage) {
ta = new TextArea("$");
ta.setOnKeyTyped(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
{
input = input.concat(event.getCharacter());
System.out.println(input);
}
}
});
final KeyCombination keyComb1 = new KeyCodeCombination(KeyCode.C,
KeyCombination.CONTROL_DOWN);
ta.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
getOutPut(input);
input = "";
System.out.println("Command Sent");
} else if (keyComb1.match(event)) {
System.out.println("Control+C pressed");
}
}
});
HBox root = new HBox();
root.getChildren().add(ta);
pb = new ProcessBuilder("bash");
try {
process = pb.start();
} catch (IOException ex) {
Logger.getLogger(JavaFXConsole.class.getName()).log(Level.SEVERE, null, ex);
}
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public void getOutPut(String command) {
Thread outputThread = new Thread(new Runnable() {
#Override
public void run() {
try {
BufferedReader stdInput, stdError;
stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
OutputStream out;
out = process.getOutputStream();
out.write(command.getBytes());
//out.flush();
out.close();
// read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
String output = "";
int ocounter = 0;
while ((s = stdInput.readLine()) != null) {
ocounter++;
System.out.println(s);
String str = s;
Platform.runLater(new Runnable() {
#Override
public void run() {
ta.appendText(">"+str + "\n");
}
});
}
output = "";
ocounter = 0;
// read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
ocounter++;
System.out.println(s);
String str = s;
Platform.runLater(new Runnable() {
#Override
public void run() {
ta.appendText("*"+str + "\n");
}
});
}
Platform.runLater(new Runnable() {
#Override
public void run() {
ta.appendText("$");
}
});
// stdError.close();
// stdInput.close();
} catch (IOException ex) {
Logger.getLogger(JavaFXConsole.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
outputThread.start();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
Any suggestion will be helpful. :)
Edit : 1
Did Improved a little , But Now getting exception, Can execute only One Command
If i don't close the stream in out.close();. Command will not execute.
Jan 22, 2015 10:54:57 PM javafxconsole.JavaFXConsole$2 handle
SEVERE: null
java.io.IOException: Stream closed
at java.lang.ProcessBuilder$NullOutputStream.write(ProcessBuilder.java:433)
at java.io.OutputStream.write(OutputStream.java:116)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
at java.io.FilterOutputStream.close(FilterOutputStream.java:158)
at javafxconsole.JavaFXConsole$2.handle(JavaFXConsole.java:69)
at javafxconsole.JavaFXConsole$2.handle(JavaFXConsole.java:58)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$KeyHandler.process(Scene.java:3931)
at javafx.scene.Scene$KeyHandler.access$1800(Scene.java:3877)
at javafx.scene.Scene.impl_processKeyEvent(Scene.java:2006)
at javafx.scene.Scene$ScenePeerListener.keyEvent(Scene.java:2468)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:197)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$KeyEventNotification.run(GlassViewEventHandler.java:147)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleKeyEvent(GlassViewEventHandler.java:227)
at com.sun.glass.ui.View.handleKeyEvent(View.java:544)
at com.sun.glass.ui.View.notifyKey(View.java:954)
at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
at com.sun.glass.ui.gtk.GtkApplication.lambda$null$45(GtkApplication.java:126)
at com.sun.glass.ui.gtk.GtkApplication$$Lambda$42/379110473.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
I solved the problem, there was no need to close the streams. Only append \n at the end of each command and flush the stream. Speacial thanks to Julio Gessar my friend which provided me solution after giving a single look to code. Here is the code. I hope this code can be used to create custom terminals or terminal emulators using Java and JavaFX. Thanks to #colti for responding to my question.
Here is the code :
/**
*
* #author nika
*/
public class JavaFXConsole extends Application {
ProcessBuilder pb;
Process process;
TextArea ta;
String input = "";
int counter = 0;
BufferedReader stdInput, stdError;
OutputStream out;
//static BufferedReader stdInput, stdError;
//static Thread outputThread;
#Override
public void start(Stage primaryStage) throws InterruptedException {
ta = new TextArea("/bin/bash\n");
ta.setOnKeyTyped(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
{
input = input.concat(event.getCharacter());
System.out.println(input);
}
}
});
final KeyCombination keyComb1 = new KeyCodeCombination(KeyCode.C,
KeyCombination.CONTROL_DOWN);
ta.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER) {
try {
//getOutPut(input+"\n");
String command = input.replaceAll("\r", "") + "\n";
command = input.replaceAll("\b", "");
out.write(command.getBytes());
out.flush();
//getOutPut(command);
input = "";
System.out.println("Command Sent");
} catch (IOException ex) {
Logger.getLogger(JavaFXConsole.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (keyComb1.match(event)) {
System.out.println("Control+C pressed");
}else if (event.getCode()== KeyCode.BACK_SPACE){
// input=input.substring(0, input.length()-1);
// System.out.println(input);
}
}
});
HBox root = new HBox();
root.getChildren().add(ta);
pb = new ProcessBuilder("/bin/bash");
new Thread(new Runnable() {
#Override
public void run() {
try {
process = pb.start();
stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
//OutputStream out;
out = process.getOutputStream();
StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR");
// any output?
StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), "OUTPUT");
// start gobblers
outputGobbler.start();
errorGobbler.start();
process.waitFor();
} catch (IOException ex) {
Logger.getLogger(JavaFXConsole.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(JavaFXConsole.class.getName()).log(Level.SEVERE, null, ex);
}
}
}).start();
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
private class StreamGobbler extends Thread {
InputStream is;
String type;
private StreamGobbler(InputStream is, String type) {
this.is = is;
this.type = type;
}
#Override
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(type + "> " + line);
String str =line;
Platform.runLater(new Runnable() {
#Override
public void run() {
ta.appendText(">" + str + "\n");
}
});
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}

Can not print in Text area from same class?

I want to print in the text area named arena. I am calling the append method from the same class with no luck so far. How to print a string in a text area??
public class Chat_window extends javax.swing.JFrame implements Runnable {
public static DataInputStream in = null;
public static PrintStream out = null;
private static Socket cs = null;
private static BufferedReader zz;
private static boolean alive = true;
public Chat_window() {
initComponents();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
Chat_window w=new Chat_window();
w.setVisible(true);
}
});
try {
cs = new Socket("localhost", 3333);
out = new PrintStream(cs.getOutputStream());
zz = new BufferedReader(new InputStreamReader(System.in));
in = new DataInputStream(cs.getInputStream());
} catch (Exception ex) {
System.out.println(ex);
}
if (cs != null && out != null && in != null) {
try {
new Thread(new Chat_window()).start();
while (alive) {
out.println(zz.readLine().trim());
}
out.close();
in.close();
cs.close();
} catch (Exception error) {
System.out.println(error);
}
}
}
#Override
public void run() {
try {
while ((m = in.readLine()) != null) {
**arena.append(m);** //This line doesnt work
System.out.println(m);
}
} catch (Exception e) {
System.out.println(e);
}
}
// Variables declaration
private java.awt.TextArea arena;
private java.awt.TextArea textArea2;
private java.awt.TextArea usrchat;
// End of variables declaration
}
Try to replace it with arena.setText(arena.getText()+"\n"+m);
Or
arena.setText(arena.getText()+m);
If you don't want to add a new line in between :)

Categories