Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Correct usage of InvokeLater ?

 
Derek Drever
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a problem updating a text area within a scroll pane. I am trying to update the text area from a seperate thread and then move the scroll bar to display the latest text, however the text area keeps getting corrupted. I am using InvokeLater to handle the scroll bar movement. My code is detailed below and I would be grateful if anybody has an idea as to where I am going wrong.
Regards,
Derek.
public class Task {
JTextArea textArea;
public Task(JTextArea textArea) {
this.textArea = textArea;
}
public void runTask(String command) {
p = null;
Output display = new Output(textArea);
try {
p = Runtime.getRuntime().exec(command);
}
catch (IOException e) {
e.printStackTrace();
System.exit( -1);
}
StreamProcess in = new StreamProcess(p.getInputStream(), display);
StreamProcess err = new StreamProcess(p.getErrorStream(), display);
in.start();
err.start();
}
}
class StreamProcess extends Thread {
InputStream in;
Output display;
public StreamProcess(InputStream in, Output display) {
this.in = in;
this.display = display;
}
public void run() {
try {
String sin = "";
BufferedReader input = new BufferedReader(new InputStreamReader(in));
while (sin != null) {
if ((sin = input.readLine()) != null)
display.append(sin);
}
}
catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
}
class Output {
private JTextArea screen;
private String buffer = "";
public Output(){}
public Output(JTextArea screen) {
this.screen = screen;
}
public synchronized void append(String s) {
if (screen != null) {
try {
screen.append(s + "\n");
EventQueue.invokeLater(new TextUpdate(screen));
}
catch(Exception ex){}
}
else {
buffer = buffer + s;
}
}
public String getBuffer() {
return buffer;
}
}
class TextUpdate implements Runnable {
JTextArea display;
JScrollBar sb;
String s;
public TextUpdate(JTextArea display) {
this.display = display;
this.sb = ((JScrollPane)display.getParent().getParent()).getVerticalScrollBar();
}
public void run() {
sb.setValue(sb.getMaximum());
}
}
 
Garandi Garandi
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
use the following, it might help

Thank you
Garandi
 
Derek Drever
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How does that differ from what I am doing ?
Regards,
Derek.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!