我创建了一个带有一些标签的JFrame,我希望我的程序暂停,直到单击某个标签。这是我的代码:
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");
}
}
在点击label2之前,我不希望打印“DONE”。如何让程序等到单击label2?
答案 0 :(得分:0)
在侦听器中添加一个标志,在单击时切换它。
boolean clicked = false;
label2.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e) {
//return to start()
clicked = true;
}
});
在打印“完成”之前,请先睡一觉。
while(clicked == false){
try {
Thread.sleep(200);
} catch(InterruptedException e) {
}
}
确保标志为volatile