Hello,
I have to print three threads simultaneously to a text area. I think I have what I need in this program, but I am still getting compiler errors. Any suggestions?
Thanks, Mary Ellen
package Chapter13;
import Chapter8.MyFrameWithExitHandling;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PrintThreadsToTextArea extends MyFrameWithExitHandling
implements ActionListener
{
private JTextArea jta;
//public StringBuffer buf = new StringBuffer();
public JButton jbt;
// Main method
public static void main(
String[] args)
{
PrintThreadsToTextArea frame = new PrintThreadsToTextArea();
frame.pack();
frame.center();
frame.setSize(400,300);
frame.setVisible(true);
}
//Constructor
public PrintThreadsToTextArea()
{
setTitle("Print Threads to Text Area");
//Create panel p to hold the tesxt field
JPanel p = new JPanel();
p.setLayout(new FlowLayout());
p.add(jta = new JTextArea());
//Create scroll pane to hold text area
JScrollPane scrollPane = new JScrollPane(jta = new JTextArea());
//set line wrap
jta.setLineWrap(true);
//set FlowLayout for the frame and add components to it
getContentPane().setLayout(new BorderLayout());
getContentPane().add(scrollPane, BorderLayout.CENTER);
getContentPane().add(p, BorderLayout.SOUTH);
//register listeners
jta.addActionListener(this);
jbt.addActionListener(this);
}
//Action event handler
// 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();
public void actionPerformed(ActionEvent e)
{
jta.append(jta.getText().trim());
}
// The
thread class for printing a specified character
// in specified times
class PrintChar extends Thread
{
private char charToPrint;
private int times;
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);
}
}
class PrintNum extends Thread
{
private int lastNum;
public PrintNum(int n)
{
lastNum = n;
}
public void run()
{
for (int i=1; i <= lastNum; i++)
System.out.print(" " + i);
}
}
}