2015-05-03 23 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"); 
     } 
    } 
}