我正在为一个程序编写GUI,该程序允许用户接受或拒绝发送到侦听服务器套接字的请求。我通过使用DoYouAcceptWindow
和打开它的另一段代码来实现这一点。
DoYouAcceptWindow.java
中的代码如下所示
public class DoYouAcceptWindow extends JFrame implements MouseListener{
private short d = 0;
private JButton accept;
public DoYouAcceptWindow() {
setLayout(new FlowLayout());
accept = new JButton("Accept");
accept.addMouseListener(this);
add(accept);
pack();
setVisible(true);
}
public short getDecided() {
return d;
}
@Override
public void mouseClicked(MouseEvent e) {
if (e.getSource().equals(accept)) {
System.out.println("Accepted");
d = 2;
}
}
}
(我已经删除了许多不必要的函数,以及拒绝请求的能力,仅仅是为了更容易阅读)。
以及使用上述类的代码:
while (true) {
DoYouAcceptWindow w = new DoYouAcceptWindow();
short decided = w.getDecided();
while (decided == 0) {
decided = w.getDecided();
}
System.out.println("Done!");
w.dispose();
if (w.getDecided() == 2) {
break;
}
}
(此代码还删除了许多不必要的部分)
当你按下这个按钮时,它会像它应该的那样打印“接受”(我假设它设置了d=1或2)。但是,它不会跳出while循环。但是,当我在while循环中添加一个print语句时(如下所示):
while (decided == 0) {
decided = w.getDecided();
System.out.println(0);
}
它自己修好了。如果我在调试模式下运行它(在eclipse中),它会修复自己。为什么在没有print语句的情况下,它不跳出while循环?我怎么才能修好它呢?(不添加打印语句)
发布于 2020-03-01 11:55:41
不能肯定地说,但是有了描述,这可能是内存可见性问题。
您能试着声明这个值易失性吗?
private volatile short d = 0;
发布于 2020-03-01 11:36:04
您的问题是,JFrame是非模式的,这意味着它不会阻塞调用代码的程序流,所以event循环将永远重复,阻塞Swing事件线程,并使应用程序变得无用。
一种解决方案是使用模态对话框,如模态JDialog或JOptionPane (这实际上是一个伪装的模态JDialog )。
例如,
import javax.swing.*;
public class DoYouAcceptEg {
public static void main(String[] args) {
int response = JOptionPane.DEFAULT_OPTION;
while (response != JOptionPane.YES_OPTION && response != JOptionPane.NO_OPTION) {
response = JOptionPane.showConfirmDialog(null, "Do you accept?",
"Accept?", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
if (response == JOptionPane.YES_OPTION) {
System.out.println("Accepted");
} else if (response == JOptionPane.NO_OPTION) {
System.out.println("Rejected");
} else {
System.out.println("Undecided");
}
}
}
}
https://stackoverflow.com/questions/60478924
复制相似问题