我有一些類與2方法。第一種方法是調用確認對話框,第二種是線程偵聽器等待完成狀態。如果偵聽器被執行,我想關閉確認對話框。可能嗎?從方法
我的代碼:
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);
}
}
你可以用正確的結果,檢查它,當你調用這個代碼cancelDialog.setValue(JOptionPane.CANCEL_OPTION)該樣品線;那時候沒有Joptionpane的實例。爲什麼零點的表達。 – 2013-05-04 15:04:58
你可以寫更多關於檢查結果嗎? – 2013-05-04 15:25:19
我不想讓你試圖使用代碼,請參閱嘗試調用cancelDialog.setValue時,cacelDialog的實例爲NULL,因爲JoptionPane會在您單擊確定/取消後自動關閉對話框。所以爲什麼你需要嘗試SetCancel(),問題是ShowDialog,應用程序不能點擊任何其他表單實體。關閉後,取消對話框中的消息爲空。 – 2013-05-04 15:55:41