I'm trying to randomly generate a string and constantly update a JTextArea. I know the program gets hung up in the runTest() method in infinite loop. I'm trying to loop and display this result until the user hits a stop button. Any advice? Thanks
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class MyApplication extends JFrame {
private JTextArea textArea;
private JButton b;
private String toChange = "";
// Called from non-UI thread
private void runQueries() {
while (true) {
runTest();
updateProgress();
}
}
public void runTest() {
while (true) {
if (toChange.length() > 10) {
toChange = "";
}
Random rand = new Random();
toChange += rand.nextInt(10);
}
}
private void updateProgress() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(toChange);
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyApplication app = new MyApplication();
app.setVisible(true);
}
});
}
private MyApplication() {
this.setLayout(null);
this.setResizable(false);
this.setLocation(100, 100);
this.setSize(900, 600);
final Panel controlPanel = new Panel();
controlPanel.setLayout(new BorderLayout());
controlPanel.setSize(600, 200);
controlPanel.setLocation(50, 50);
setDefaultCloseOperation(this.EXIT_ON_CLOSE);
textArea = new JTextArea("test");
textArea.setSize(100, 100);
textArea.setLocation(200, 200);
this.add(textArea);
JButton b = new JButton("Run query");
b.setSize(100, 75);
b.setLocation(100, 50);
this.add(b);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread queryThread = new Thread() {
public void run() {
runQueries();
}
};
queryThread.start();
}
});
}
}