Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

using thread class to print to a text area

 
MaryEllen Volb
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello!
As a class assignment, I have to modify the following code to display the output to a text area(instead of just to the DOS window). Any hints as to how I should attempt this? THANKS!!!
This program creates and runs three threads.
first prints letter 'a' 100 times.
second prints letter 'b' 100 times.
third prints integers 1 through 100.
NOW: I NEED IT TO PRINT TO A TEXT AREA, NOT TO THE DOS WINDOW!

Thanks again, MARY ELLEN!
// TestThreads.java: Define threads using the Thread class
package Chapter13;
public class TestThreads
{
// Main method
public static void main(String[] args)
{
// Create threads
PrintChar printA = new PrintChar('a', 100);
PrintChar printB = new PrintChar('b', 100);
PrintNum print100 = new PrintNum(100);
// Start threads
print100.start();
printA.start();
printB.start();
}
}
// The thread class for printing a specified character
// in specified times
class PrintChar extends Thread
{
private char charToPrint; // The character to print
private int times; // The times to repeat
// Construct a thread with specified character and number of
// times to print the character
public PrintChar(char c, int t)
{
charToPrint = c;
times = t;
}
// Override the run() method to tell the system
// what the thread will do
public void run()
{
for (int i=1; i < times; i++)
System.out.print(charToPrint);
}
}
// The thread class for printing number from 1 to n for a given n
class PrintNum extends Thread
{
private int lastNum;
// Construct a thread for print 1, 2, ... i
public PrintNum(int n)
{
lastNum = n;
}
public void run()
{
for (int i=1; i <= lastNum; i++)
System.out.print(" " + i);
}
}
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First you need to create a Window of some sort in main - Frame would be a good choice. Don't forget to set it's size and make it visible. Then you need to create a TextArea and add it to the Frame.
Now all the places that you are doing println() instead you .append() the output to the TextArea. You will need to add your own \n to get a new line.
That should be it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic