Reputation: 23
I have this method to update value of a TextArea:
private void startShow(String fileName, TextArea textArea) throws InterruptedException{
textArea.setVisible(true);
int ptr=0;
String[] tokens=s.split(" ");
while (ptr<tokens.length){
try {
Thread.sleep(1000+textSpeed*50); //1000 milliseconds is one second
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
textArea.setText(tokens[ptr]);
ptr++;
}
}
Here, textSpeed is a class variable that is updated by clicking a button like this:
Button button_1 = new Button("+");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textSpeed++;
}
});
While my code is in the while loop, the button is unclickable and thus textSpeed cannot change. My question is:
1) Can I make the button clickable without multithreading? I just started Java Swing and I have no previous experience with multithreading so I don't know if there's a simpler solution.
2) If multithreading is necessary, how would I implement that in the above code? Any tips or suggestions would be great. Thanks!
Upvotes: 0
Views: 41
Reputation: 285403
Regarding your questions:
1) Can I make the button clickable without multithreading? I just started Java Swing and I have no previous experience with multithreading so I don't know if there's a simpler solution.
The direct answer is no, you must use some form of multithreading, but you could do your threading indirectly by using a Swing Timer to do the delays for you. For details, check the tutorial. For your program, you'd likely use the actualSpeed
to set the delay time of your Timer object.
2) If multithreading is necessary, how would I implement that in the above code? Any tips or suggestions would be great. Thanks!
This question is a bit broad, perhaps overly broad, and in this situation, I find that the best answer is for you to read the tutorials. For Swing Threading, check Concurrency in Swing. Then after digesting this information if later you have a more specific question, it will be much more easily answered with a specific answer.
Upvotes: 2