单击时如何更改选项窗格“确定”按钮的功能?

时间:2015-05-03 21:00:25

标签: java swing joptionpane

说你有这样的事情......

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

这会弹出一个对话框,其中显示消息“Whatever”和一个OK按钮。我可以在此确定按钮中添加ActionListener吗?有没有办法可以改变它点击时的作用?

2 个答案:

答案 0 :(得分:3)

如果你可以显示OK / Cancel按钮,那么使用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");
      }
   }
}

答案 1 :(得分:-1)

是的,你可以在其上添加动作列表器,你可以用它打开其他弹出窗口