Reputation: 464
I have been trying to get this thread to wait, but it doesnt wait or throw an exception or do anything... (I created a new Thread to run the thread because otherwise my gui freezes due to calling the wait method on the edt)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Sandbox extends JFrame {
boolean paused = false;
Thread thread = new Thread() {
public void run() {
while(true) {
System.out.println("running...");
}
}
};
private JButton button;
public Sandbox() throws Exception {
thread.start();
setSize(300, 150);
setLocationRelativeTo(null);
setDefaultCloseOperation(3);
add(button = new JButton("Pause"));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Thread() {
public void run() {
synchronized(thread) {
try {
if(button.getText().equals("Pause")) {
thread.wait();
button.setText("Resume");
} else if(button.getText().equals("Resume")) {
thread.notify();
button.setText("Pause");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}});
setVisible(true);
}
public static void main(String[] args) throws Exception {
new Sandbox();
}
}
Upvotes: 1
Views: 112
Reputation: 13222
If you are comparing strings you need to use equals()
and not ==
if(button.getText().equals("Pause")) {
thread.wait();
button.setText("Resume");
} else if(button.getText().equals("Resume")) {
thread.notify();
button.setText("Pause");
}
But using wait and notify will probably not really do what you want.
Upvotes: 1