2015-05-03 22 views
-1

說你有這樣的事情....如何更改選項窗格「確定」按鈕在點擊時的功能?

public class ActionEvents { 
    public static void main(String[] args){ 
     JOptionPane.showMessageDialog(null, "Whatever"); 
    } 
} 

這應該彈出一個對話框,顯示消息「什麼」和確定按鈕。我可以添加一個ActionListener到這個OK按鈕嗎?有什麼方法可以改變點擊時的功能嗎?

+2

爲什麼你要連接一個ActionListener到這個按鈕?按下時你想採取什麼行動? – copeg

+0

這將幫助你,看到一個自定義對話框的這個[示例](http://www.java2s.com/Tutorial/Java/0240__Swing/extendsJDialogtocreateyourowndialog.htm)。 –

+0

點擊好的按鈕時,你想要做什麼? – MadProgrammer

回答

-1

是的,你可以在上面添加行爲聽者,你可以用它

+2

你能解釋一下嗎? –

+0

您必須通過擴展JDialog類 –

+0

@Jainik Bakaraniya創建客戶對話框,請使用代碼示例。 – Ndumiso

3

打開其他彈出窗口,如果你確定出確定/取消按鈕,然後用JOptionPane.showConfirmDialog和響應返回的值,如果它代表JOptionPane.OK_OPTION:

public static void main(String[] args) { 
    int optionType = JOptionPane.OK_CANCEL_OPTION; 
    int messageType = JOptionPane.PLAIN_MESSAGE; 
    int value = JOptionPane.showConfirmDialog(null, "Whatever", 
     "Whatever Fun", optionType, messageType); 
    if (value == JOptionPane.OK_OPTION) { 
    System.out.println("OK pressed"); 
    } 
} 

否則,你可以使用JOptionPane.showOptionsDialog只顯示OK按鈕:

import javax.swing.Icon; 
import javax.swing.JOptionPane; 

public class JOptionPaneFun { 
    public static void main(String[] args) { 
     int optionType = JOptionPane.OK_CANCEL_OPTION; 
     int messageType = JOptionPane.PLAIN_MESSAGE; 
     int value = JOptionPane.showConfirmDialog(null, "Whatever", 
      "Whatever Fun", optionType, messageType); 
     if (value == JOptionPane.OK_OPTION) { 
     System.out.println("OK pressed"); 
     } 

     String message = "Whatever"; 
     String title = "JOptionPane Fun"; 
     Icon icon = null; 

     Object[] options = { "OK" }; 
     Object initialValue = options[0]; 
     int anotherValue = JOptionPane.showOptionDialog(null, message, title, 
      optionType, messageType, icon, options, initialValue); 
     if (anotherValue >= 0 && initialValue.equals(options[anotherValue])) { 
     System.out.println("OK Pressed Again"); 
     } 
    } 
}