I created a JFrame with some labels on it and i want my program to pause until a certain label is clicked. Here 's my code:
package test;
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class GUI {
public GUI(){
}
private void createFrame(){
JFrame frame=new JFrame("TEST");
JLabel label1=new JLabel("LABEL1");
JLabel label2=new JLabel("LABEL2");
JLabel label3=new JLabel("LABEL3");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.add(label1,BorderLayout.PAGE_START);
frame.add(label2,BorderLayout.CENTER);
frame.add(label3,BorderLayout.PAGE_END);
label1.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e) {
//do something
}
});
label2.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e) {
//return to start()
}
});
label3.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e) {
//do something
}
});
}
public void start(){
createFrame();
System.out.println("DONE");
}
}
I don't want "DONE" to be printed before i click on label2. How can I make the program wait until label2 is clicked?
Add a flag in the listener, that toggles it on the click.
boolean clicked = false;
label2.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e) {
//return to start()
clicked = true;
}
});
And before printing "DONE", sleep on it.
while(clicked == false){
try {
Thread.sleep(200);
} catch(InterruptedException e) {
}
}
Make sure the flag is volatile