2011-12-15 18 views
6

我有一個自定義對話框,收集用戶的兩個字符串。創建對話框時,我使用OK_CANCEL_OPTION作爲選項類型。 Evertyhings的作品除了當用戶點擊取消或關閉對話框時,它具有相同的效果,點擊確定按鈕。JOptionPane.createDialog和OK_CANCEL_OPTION

我該如何處理取消和關閉事件?

繼承人的代碼,我說的是:

JTextField topicTitle = new JTextField(); 
JTextField topicDesc = new JTextField(); 
Object[] message = {"Title: ", topicTitle, "Description: ", topicDesc}; 

JOptionPane pane = new JOptionPane(message, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION); 
JDialog getTopicDialog = pane.createDialog(null, "New Topic"); 
getTopicDialog.setVisible(true); 

// Do something here when OK is pressed but just dispose when cancel is pressed. 

回答

4

我想一個更好的選項,供您是使用以下代碼

JTextField topicTitle = new JTextField(); 
    JTextField topicDesc = new JTextField(); 
    Object[] message = {"Title: ", topicTitle, "Description: ", topicDesc}; 


    Object[] options = { "Yes", "No" }; 
    int n = JOptionPane.showOptionDialog(new JFrame(), 
      message, "", 
      JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, 
      options, options[1]); 
    if(n == JOptionPane.OK_OPTION){ // Afirmative 
     //.... 
    } 
    if(n == JOptionPane.NO_OPTION){ // negative 
     //.... 
    } 
    if(n == JOptionPane.CLOSED_OPTION){ // closed the dialog 
     //.... 
    } 

使用showOptionDialog方法,你正在根據用戶所做的結果,所以你不需要做任何事情,除了解釋這一結果

+1

感謝編輯+1 – mKorbel 2011-12-15 15:03:06

+0

非常非常感謝你們。使用showOptionDialog代替createDialog的作品。 – philb28 2011-12-15 15:10:54

2

JOptionPane你的情況

JOptionPane.OK_OPTION 
JOptionPane.CLOSED_OPTION 
JOptionPane.CANCEL_OPTION 

簡單的例子回報here

0

Class JOptionPane。開始閱讀在點文本「的例子:」

這是我的完整的例子:

import javax.swing.JDialog; 
import javax.swing.JOptionPane; 
import javax.swing.JTextField; 

public class Main { 
public static void main(String[] args) { 

    JTextField topicTitle = new JTextField(); 
    JTextField topicDesc = new JTextField(); 


    Object[] message = {"Title: ", topicTitle, "Description: ", topicDesc}; 

    JOptionPane pane = new JOptionPane(message, 
      JOptionPane.PLAIN_MESSAGE, 
      JOptionPane.YES_NO_CANCEL_OPTION); 

    JDialog getTopicDialog = pane.createDialog(null, "New Topic"); 
    getTopicDialog.setVisible(true);   

    Object selectedValue = pane.getValue(); 
    int n = -1; 


    if(selectedValue == null) 
     n = JOptionPane.CLOSED_OPTION;  
    else 
     n = Integer.parseInt(selectedValue.toString()); 


    if (n == JOptionPane.YES_OPTION){ 
     System.out.println("Yes"); 
    } else if (n == JOptionPane.NO_OPTION){ 
     System.out.println("No"); 
    } else if (n == JOptionPane.CANCEL_OPTION){ 
     System.out.println("Cancel"); 
    } else if (n == JOptionPane.CLOSED_OPTION){ 
     System.out.println("Close"); 
    }  
} 
}