我有一些课程有两种方法。第一种方法是调用确认对话框,第二种是线程侦听器等待完成状态。如果执行了侦听器,我想关闭确认对话框。可能吗?
我的代码:
public class NewNetworkGame implements ThreadListener {
ReadMsg read;
Network net;
// my dialog
JOptionPane cancelDialog;
boolean accepted = false;
boolean readStopped = false;
public NewNetworkGame(Network net) {
this.net = net;
read = new ReadMsg(this.net);
ThreadHandler rm = read;
rm.addListener(this);
rm.start();
JPanel cancelConn = new JPanel();
cancelConn.add(new JLabel("Waiting for host response..."));
// showing dialog
int result = cancelDialog.showConfirmDialog(null, cancelConn, "Host response", JOptionPane.CANCEL_OPTION);
// client clicked on cancel option while thread is still reading host response
if (result == JOptionPane.CANCEL_OPTION && !accepted && !readStopped) {
net.sendReject();
}
if (!readStopped) {
read.interrupt();
}
}
@Override
public void notifyOfThreadComplete(Thread thread) {
readStopped = true;
if (net.getAcceptMsg().equals(read.getStr())) {
accepted = true;
}
// closing dialog
cancelDialog.setValue(JOptionPane.CANCEL_OPTION);
// generates: java.lang.NullPointerException
}
}
我java.lang.NullPointerException
从cancelDialog.setValue(JOptionPane.CANCEL_OPTION)
侦听器处理程序中获取。你能帮助如何关闭确认对话框吗?
更新解决方案。 工作代码:
public class NewNetworkGame implements ThreadListener {
ReadMsg read;
Network net;
boolean accepted = false;
boolean readStopped = false;
final JDialog dialog = new JDialog();
public NewNetworkGame(Network net) {
this.net = net;
read = new ReadMsg(this.net);
ThreadHandler rm = read;
rm.addListener(this);
rm.start();
JPanel cancelConn = new JPanel();
cancelConn.add(new JLabel("Waiting for host response..."));
Object[] options = {"Abort"};
JOptionPane.showOptionDialog(dialog, cancelConn, "Host response", JOptionPane.CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
System.out.println("clicked");
if (!accepted && !readStopped) {
System.out.println("aborted");
net.sendReject();
}
if (!readStopped) {
read.interrupt();
}
}
@Override
public void notifyOfThreadComplete(Thread thread) {
readStopped = true;
if (net.getAcceptMsg().equals(read.getStr())) {
accepted = true;
}
dialog.setVisible(false);
}
}