Skip to main content

OutOfMemory Error when updating JTextArea

2 replies [Last post]
forrestert
Offline
Joined: 2008-11-28
Points: 0

I believe I have a threading issue and am searching for ideas to help solve it.
My JDK1.3.1 GUI sets of an external process when a button is clicked for example:
ProcThread pt;
final SwingWorker worker = new SwingWorker() {
ProcThread pt = null;

public Object construct() {
pt = new ProcThread(cmd, textArea);
pt.run();
return pt;

}

};
worker.start();

ProcThread is an ordinary Class, the sets off an external
process using:

Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);

The next job is to take the output from the external process "proc.getInputStream()" and update a JTextArea every time a line of output is written.

I do this is a separate class that extends Thread "StreamGobbler extends Thread". In its run method I update the TextArea as such:

while ((line = br.readLine()) != null) {
textArea.setText(textArea.getText() + type + ">" + line + "\n");
Rectangle taRect = textArea.getBounds();
int taY = textArea.getHeight();
if (taY > lastTaY) {
lastTaY = taY;
Rectangle r = new Rectangle(0, taY - taHeight , taWidth, taHeight);
textArea.scrollRectToVisible(r);
}
}

Updating the TextArea like this is causing the problem. Most examples of this kind of problem, deal with the case where you set a thread going that does a long job, then when its finished you update the textArea, but I want to update the TextArea as each line of output from the external process is captured.

I would really appreciate some help!

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
viravan
Offline
Joined: 2003-06-23
Points: 0

instead of:

while ((line = br.readLine()) != null) {
textArea.setText(textArea.getText() + type + ">" + line + "\n");

try:

while ((line = br.readLine()) != null) {
textArea.append(type + ">" + line + "\n");

;o)

V.V.

acechase
Offline
Joined: 2003-12-02
Points: 0

Hi,

It looks like you're making a lot of calls to the textArea object in your StreamGobbler class. You may want to try and consolidate your calls to textArea by updating textArea every nth call to readLine. Also, you may try holding the text in a StringBuffer and appending to that, then setting the textArea text with the StringBuffer's current string rather than relying on the TextArea's internal string storage for storing the current state of the string.

This doesn't directly address your problem, but it may help. It's hard to say what else is going on given the code provided. Coudl the outOfMemoryException be getting thrown by the "cmd" you are passing to rt.exec?

Cheers,
Andrew

Message was edited by: acechase