ActionListener for JOptionPane.showConfirmDialog

Is it possible to handle JOptionPane.showConfirmDailog 's button click events through action listeners?
I want to execute some code on the "Save" button click and want to do it like my JFileChooser window stays in the background until either of the Yes,No or Cancel buttons of the showConfirmDialog is pressed.In fact I'm able to get the state of the button pressed using,
int i=JOptionPane.showConfirmDialog(null,"Confirm file overwrite?")but can't make the showConfirmDialog window stay in the background,,,
Can anybody please help?
Thanks in advance...

There are forums specifically for GUI questions.
I believe there is also a forum for international issues.

Similar Messages

  • Tooltip for a JOptionPane.showConfirmDialog??

    I can't get this to work, any ideas on how to reference the OK & Cancel buttons of the "JOptionPane.showConfirmDialog" and create a custom tooltip for each??
    // --------- test to see if the current file was modified and give an option to save first.
    if (changed)
    // ----- display pop-up alert --------------------------------------------------------------
    int confirm = JOptionPane.showConfirmDialog(null,
    "Click OK to discard current changes, \n or Cancel to save before proceeding.", // msg
    "Unsaved Modifications!", // title
    JOptionPane.OK_CANCEL_OPTION, // buttons displayed
                        // JOptionPane.ERROR_MESSAGE
                        // JOptionPane.INFORMATION_MESSAGE
                        // JOptionPane.PLAIN_MESSAGE
                        // JOptionPane.QUESTION_MESSAGE
    JOptionPane.WARNING_MESSAGE,
    null);
    // -- set the tool tip for the buttons here -- ??????
    // public Point getToolTipLocation( MouseEvent event);
    // public JToolTip createToolTip( );
    // toolTipText
    // Point getToolTipLocation( MouseEvent MOUSE_CLICKED);
    JOptionPane.getToolTipLocation(OK_OPTION, Click to discard current changes."")
    // OKButton.setToolTipText("Click to discard current changes.");
    // CancelButton.setToolTipText("Click to save the current file.");
    if (confirm != JOptionPane.YES_OPTION)
    { //user wants to save changes
    try {
    // save the file
    catch(Exception e) {}
    } // close "if (changed)"
    // ----- display pop-up alert --------------------------------------------------------------

    The renderer code has this structure:
    public class MyRenderer extends DefaultTreeCellRenderer {
         public Component getTreeCellRendererComponent(JTree tree, Object value, boolean isSelected, boolean isExpanded, boolean isLeaf, int index, boolean hasFocus) {
              JTextPanel pane = new JTextPanel();
              pane.setLayout(new FlowLayout(FlowLayout.LEFT, 2, 0));
              if (data instanceof MyDataObject) {
                   MyDataObject myObj = (MyDataObject)data;
                   JLabel label = new JLabel();
                   label.setIcon(myObj.getIcon());
                   label.setText(myObj.getInfo());
                   label.setToolTipText("MyTooltip");
                   pane.add(label);
              return pane;
    Thomas Wiedmann

  • JOptionPane.showConfirmDialog requires two key strokes with Java SE 6.

    I have been using the following line of code:
    rc = JOptionPane.showConfirmDialog( comp, objects, "Warning",
    JOptionPane.YES_NO_OPTION,
    JOptionPane.INFORMATION_MESSAGE);
    with no problems with plug-in 1.4 and 1.5. Now with 1.6, when I choose Yes/No/Cancel, the first time I press the button nothing happens, the second time I press the button the action takes place.
    I have been searching for information on this and have not found any known issues (yet). Does anyone have any ideas?

    further investigation shows that this only happens when the component is a JComboBox. I found a new bug that seems to be the same issue:
    http://bugs.sun.com./bugdatabase/view_bug.do?bug_id=6817939
    When calling JOptionPane.showConfirmDialog from an ActionListener called by a JComboBox, there is 2 issues:
    * the focus is not given to the confirm dialog

  • Problem w/JOptionPane showConfirmDialog

    Okay, I have a JOptionPane.showConfirmDialog on a JInternalFrame that works for the most part, but is doing something weird. When a user clicks the Cancel option or closes the JOptionPane, I want it simply to go away. Instead, it will pop up again, and if the user click Cancel or closes the window, it will go away, but it will take the JInternalFrame with it, which I don't want it to do. I have the code pasted below, and it should work the way I have it coded, but it don't. Anyone help??int result = JOptionPane.showConfirmDialog(CustomFrame.this, getTitle() +
       " has been changed. Would you like to save?", "Save File?", JOptionPane.YES_NO_CANCEL_OPTION,
       JOptionPane.WARNING_MESSAGE);
       switch(result)
          default:
             break;
          case JOptionPane.YES_OPTION:
             save();
             break;
          case JOptionPane.NO_OPTION:
             dispose();
             break;
          case JOptionPane.CANCEL_OPTION:
             break;
       }Now this is being triggered from the internalFrameClosing method of the InternalFrameListener interface that is implemented on a private class in my JInternalFrame constructor. And like I said, all other aspects of it work fine and when it's supposed to, but with the Cancel option or closing the JOptionPane (which would trigger the default: option from the switch construct, correct?), I want it to go away. It will pop up a second time, then go away with the JInternalFrame. Any suggestions? Thanks a lot. I'm using JDK 1.4.1 for the Macintosh (15" iMac G4).
    James

    Okay, I have a JOptionPane.showConfirmDialog on a JInternalFrame that works for the most part, but is doing something weird. When a user clicks the Cancel option or closes the JOptionPane, I want it simply to go away. Instead, it will pop up again, and if the user click Cancel or closes the window, it will go away, but it will take the JInternalFrame with it, which I don't want it to do. I have the code pasted below, and it should work the way I have it coded, but it don't. Anyone help??int result = JOptionPane.showConfirmDialog(CustomFrame.this, getTitle() +
       " has been changed. Would you like to save?", "Save File?", JOptionPane.YES_NO_CANCEL_OPTION,
       JOptionPane.WARNING_MESSAGE);
       switch(result)
          default:
             break;
          case JOptionPane.YES_OPTION:
             save();
             break;
          case JOptionPane.NO_OPTION:
             dispose();
             break;
          case JOptionPane.CANCEL_OPTION:
             break;
       }Now this is being triggered from the internalFrameClosing method of the InternalFrameListener interface that is implemented on a private class in my JInternalFrame constructor. And like I said, all other aspects of it work fine and when it's supposed to, but with the Cancel option or closing the JOptionPane (which would trigger the default: option from the switch construct, correct?), I want it to go away. It will pop up a second time, then go away with the JInternalFrame. Any suggestions? Thanks a lot. I'm using JDK 1.4.1 for the Macintosh (15" iMac G4).
    James

  • JOptionPane showConfirmDialog problem

    Hello everyone,
    I have written my own class that shows a customized confirm dialog (code is pasted below). I need to be able to tell whether the user clicks "YES", "NO" or "CANCEL".
    My main app has a panel with a JButton "Start System". When this button is clicked, the following code instantiates OperatorConfirmDialog:
         public void startNetwork(){
              confirmDialog = new OperatorConfirmDialog("Are you sure you want to start the network?");
              System.out.println("WE MADE IT TO HERE");//problem we do not get to here until confirm dialog acked
         }I referred to the examples for JOptionPane given at:
    http://java.sun.com/j2se/1.5.0/docs/api/index.html
    for examples but it doesn't seem to be working for me.
    Here is the code for OperatorConfirmDialog
    public class OperatorConfirmDialog extends JFrame {
         JOptionPane pane;
         public OperatorConfirmDialog(String message){
              pane = new JOptionPane();
              this.setDefaultLookAndFeelDecorated(true);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.getContentPane().setLayout(new BorderLayout());
              pack();
              //pane.getSelectionValues()
              pane.showConfirmDialog(this, message, "Confirm", JOptionPane.YES_NO_CANCEL_OPTION);
              Object selectedValue = pane.getValue();  //problem here
              if(selectedValue == null){
                   //do nothing...they just killed window
              }else {
                   for(int counter = 0, maxCounter = pane.getOptions().length; counter < maxCounter; counter++){
                        if(pane.getOptions()[counter].equals(selectedValue)){
                             //do something
              this.dispose();
         public JOptionPane getPane(){
              return pane;
         public static void main(String[] args) {
              OperatorConfirmDialog dialog = new OperatorConfirmDialog("Please enter a valid username.");
    }I put a break point at the line:
    if(selectedValue == null){
    When I run the debugger, confirmDialog prompts me to click "YES", "NO" or "CANCEL". I click "YES" and then arrive at the breakpoint. But, selectedValue doesn't seem to have the right value....the debugger says its value is "uninitializedValue" (literally). Any ideas?
    Thanks!

    Try this. Notice I received an int result from the showConfirmDialog() method.
    import javax.swing.*;
    import java.awt.*;
    public class OperatorConfirmDialog extends JFrame {
        JOptionPane pane;
        public OperatorConfirmDialog(String message) {
            pane = new JOptionPane();
            this.setDefaultLookAndFeelDecorated(true);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.getContentPane().setLayout(new BorderLayout());
            pack();
    // get the response from the user
            int result = pane.showConfirmDialog(this, message, "Confirm", JOptionPane.YES_NO_CANCEL_OPTION);
            if (JOptionPane.YES_OPTION == result) {
                // do what you want on 'yes' clicked
                System.out.println("User Clicked 'Yes'.");
            } else {
    // user clicked 'no' or 'cancel'... you could check result for JOptionPane.NO_OPTION or CANCEL_OPTION
                System.out.println("User Clicked either 'No' or 'Cancel'.");
            this.dispose();
        public JOptionPane getPane() {
            return pane;
        public static void main(String[] args) {
            OperatorConfirmDialog dialog = new OperatorConfirmDialog("Please enter a valid username.");
    }

  • JOptionPane.showConfirmDialog -- remember decision checkbox

    Hi
    JOptionPane.showConfirmDialog -- remember decision checkbox
    is there something to set "remember my decision" for the following dialog box i.e. this dialog sits inside a loop over a set of files
    so if i say "yes overwrite" it should remember that decision. Should i make a dialog box on my own or is there a parameter setting for this
    purpose ?
    if(currentCsvOutputFile.isFile()){
    int userConfirm = JOptionPane.showConfirmDialog(
              new JFrame(),
              currentCsvOutputFile + " already exists , Do you want to overwrite it ? " ,
              "Confirm",
              JOptionPane.YES_NO_OPTION);
    }Regards

    No need for a custom dialog, just add a JLabel and a JCheckBox to a JPanel and pass that as the message parameter.JCheckBox remember = new JCheckBox("Remember my decision");
        JPanel panel = new JPanel(new BorderLayout()); // or whatever layout you find best
        panel.add(new JLabel("File already exists , Do you want to overwrite it ? "), BorderLayout.NORTH);
        anel.add(remember, BorderLayout.SOUTH);
        int userConfirm = JOptionPane.showConfirmDialog(new JFrame(), panel, "Confirm", JOptionPane.YES_NO_OPTION);db

  • JOptionPane.showConfirmDialog  "NO" button acting as "YES" on MAC using TAB

    JOptionPane.showConfirmDialog "NO" button acting as "YES" on MAC using TAB

    Ya , I am asking question ? Why "NO" is acting as "YES" button in case of JOptionPane.showConfirmDialog on MAC using TAB.
    i.e,
    I clicked on some button, then showConfirmDialog is opened, By default the focus is on "YES" button. Now I pressed TAB button and changed to the focus to "NO" button.
    If press ENTER key --> acting "YES"
    If press SPACE key -> acting as "NO"
    Why ?
    What should I do to make it correct ?
    Am I need mention set (Key,value) pairs for UIManager in case of MAC.
    Please suggest ?

  • Adding actionListener to JOptionPane

    how do you add an actionListener to a JOptionPane?
    im using JOptionPane.showMessageDialog, and i want an event to happen when the user clicks on the "Okay" button

    Can you do something like this instead? Use a showConfirmDialog(...) istead of the showMessageDialog(...), then use the return value to determine which button the user pushed?
    int retValue = JOptionPane.showConfirmDialog(parent, message, Title, JOptionPane.OK_CANCEL_OPTION );
    if (retValue == JOptionPane.OK_OPTION)
      doOkayEvent();
    else
      doNotOkayEvent();

  • JOptionPane.showConfirmDialog in servlets

    Hi
    I am trying to show a dialog in a doPost method of a servlet. For some reason, it blocks the entire method and does not show the dialog. What gets me voiceless is that it works in the doGet method of the servlet.
    The situation is the following:
    - a first serlvet dispatches GET requests to other servlets according to the role of users.
    - in the doGet of this first servlet, a second (servlet2) is instantiated and its doGet is called;
    - in the doGet of servlet2, a HTML form (POST method) is generated;
    - when the submit button of the HTML form is pressed, the form is processed by the doPost of servlet2.
    JOptionPane.showConfirmDialog works in servlet2 only in the doGet and not in the doPost. Their code is:
    //Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    DataModule1 dm = (DataModule1) ixPageProducer1.getSessionDataModule(request.getSession());
    dm.parameterRow1.setString("empl_ini", request.getRemoteUser());
    dm.queryDataSet1.refresh();
    empl_id = dm.queryDataSet1.getInt("number");
    ixPageProducer1.servletGet(this, request, response);
    //Process the HTTP Post request
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    DataModule1 dm = (DataModule1) ixPageProducer1.getSessionDataModule(request.getSession());
    dm.queryDataSetReq.insertRow(false);
    ixPageProducer1.servletPost(this, request, response);
    JOptionPane.showConfirmDialog(null, "test" , "Request Confirmation", JOptionPane.YES_NO_OPTION);
    (I am using JBuilder and its InternetBeans to link the HTML pages with the DB).
    Many thanks in advance for helping a desperate Java beginner!!!

    I figured out that the dialog was actually generated, but "behind" my browser.You can try this to add the following either before or after the JOptionPane.showConfirmDialog:
    JOptionPane.requestFocus();
    But I think your best bet is to associate a frame with your dialog box as follows:
    Object parent = this.getParent();
    while (!(parent instanceof Frame)) parent = ((Component)parent).getParent();
    F = (Frame)parent;
    JOptionPane.showConfirmDialog(F, "test" , "Request Confirmation", JOptionPane.YES_NO_OPTION);
    If this helps, don't forget the Dukes
    ;o)
    V.V.

  • Can we add scrollbar to JOptionPane.showConfirmDialog()

    Hi,
    Can we add a scroll bar to JOptionPane.showConfirmDialog() so that the contents(messages) which are to be displayed are present in scrollbar so that the buttons will be visible to the user like OK, CANCEL.
    Currently when the message is large the buttons will not be visble in the screen.
    So, it is possible ? Or there is any other alternative for the same.
    Thanks.

    Is there another library that I have to import? I recieve this error when I try to compile...
    isPrime.java:53: cannot find symbol
    symbol : variable sb
    location: class isPrime
         JTextArea area = new JTextArea(sb.toString() );
    I have javax.swing.* imported as of right now...
         JTextArea area = new JTextArea(sb.toString());
          area.setRows(25);
          area.setColumns(100);
          area.setLineWrap(true);
          JScrollPane pane = new JScrollPane(area);
           JOptionPane.showConfirmDialog(null,
         pane,
           "Test", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
    /*         JOptionPane.showMessageDialog(null,
               printArray(array),
         "Thanks for using Reverse Array", JOptionPane.INFORMATION_MESSAGE);
    */       the comment text is what I eventually wish to print((I simply hid it from the compiler so I could play w/ the code you provided)... it is the first 'n' number of primes up to which I'd like to be able to scroll through for large prints over 100 primes.
    thx for the help

  • WindowsClosingEvent on JOptionPane.showConfirmDialog

    I have a confirmdialog but i want to be able to control what happens when i close this window instead of pressing yes or no.
    I have been reading about WindowListeners. Ive imlpemented WindowListener but i dont know how to add the windowListener to my confirmDialog.
    Heres the method i use for creating a confirmdialog
    private boolean confirmDialogue(String message) {
            int selectedOption = JOptionPane.showConfirmDialog(this, message, "Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            return (selectedOption == JOptionPane.YES_OPTION);
        }

    Okay, I could do it like this but im not sure if its the best way:
    private boolean confirmDialogue(String message) {
            int selectedOption = JOptionPane.showConfirmDialog(this, message, "Confirmation", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if(selectedOption == JOptionPane.CLOSED_OPTION)
                System.out.println("CLOSED WINDOW");
            return (selectedOption == JOptionPane.YES_OPTION);
        }

  • About JOptionPane.showConfirmDialog

    If i have this code :
    public class XFrame extends JFrame {
        private static class ExitListener extends WindowAdapter {
            int confirm = JOptionPane.showConfirmDialog(null, .......);
        public XFrame() {
            setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
            addWindowListener(new ExitListener());
    }The confirm dialog box showed in the center of screen, not in the center of XFrame instance.
    So if my screen size is bigger than XFrame size, and XFrame does not located in the center, it seems a little ugly for me.
    What should I do?. It is impossible to write :
    int confirm = JOptionPane.showConfirmDialog(this, ....) since this will refer to inner class (ExitListener), not the XFrame class. What is the correct syntax to center the confirm dialog?

    Hi this should do what you want
    public class Test extends JFrame { 
      public Test() {    
        this.setSize(600,600);
        setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);       
        this.show();
        final Test test = this;
        addWindowListener(new WindowAdapter() {
          int confirm = JOptionPane.showConfirmDialog(test,"Some info");
      public static void main(String[] args) {
        Test testApp = new Test();
    }

  • JOptionPane.showConfirmDialog()+grab focus

    Hi
    How do I get the cursor blinking in the textfield of JOptionPane.showConfirmDialog() by default when my code executes JOptionPane.showConfirmDialog() ?
    Thanks
    apoorva

    Hi Apoorva,
    Here I am giving you working code. This cocmpletely solves your problem.
    import java.awt.Rectangle;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.SwingUtilities;
    public class test extends JFrame {
         private static final long serialVersionUID = 1L;
         private JPanel jContentPane = null;
         private JButton jButton = null;
         private JPasswordField tPasswordField;
          * This method initializes jButton     
          * @return javax.swing.JButton     
         private JButton getJButton() {
              if (jButton == null) {
                   jButton = new JButton();
                   jButton.setBounds(new Rectangle(85, 121, 104, 27));
                   jButton.setText("Click");
                   jButton.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                             System.out.println("actionPerformed()"); // TODO Auto-generated Event stub actionPerformed()
    //                         JPasswordField tPasswordField = new JPasswordField(
                             tPasswordField = new JPasswordField(10);
                             tPasswordField.setEchoChar('*');
                             SwingUtilities.invokeLater(new Runnable()
                                public void run()
                                       tPasswordField.requestFocus();
                             int ret=JOptionPane.showConfirmDialog(test.this,
                                       tPasswordField,
                                       "Enter server password",
                                       JOptionPane.OK_OPTION);
              return jButton;
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        test thisClass = new test();
                        thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        thisClass.setVisible(true);
          * This is the default constructor
         public test() {
              super();
              initialize();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setSize(300, 200);
              this.setContentPane(getJContentPane());
              this.setTitle("JFrame");
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setLayout(null);
                   jContentPane.add(getJButton(), null);
              return jContentPane;
    }Now u can mark this as fixed and assign duke stars.. :-)

  • How to create a actionListener for individual JButton in a for loop?

    How to create a actionListener for individual JButton in a for loop? Can someone help me?

    Do you mean something like this?:
    JButton tempButton;
    for(int i = 0; i < 10; i++){
         tempButton = new JButton("Button " + String.valueOf(i));
         tempButton.setActionCommand("action" + String.valueOf(i));
         tempButton.addActionListener(this);
         // or tempButton.addActionLister(new ActionListener(){...});
         frame.add(tempButton);
    }

  • JOptionPane.showConfirmDialog: Tabbing between options creates wrong result

    In JOptionPane.showConfirmDialog, when pressing <tab> to move between options and then pressing <Enter> I always get a returned zero (0) no matter which button is in focus. Is this a (known) bug or am I stupid?
    I run the following code.
    import javax.swing.*;
    public class TabOptions
    public static void main (String [] args)
         int n = JOptionPane.showConfirmDialog (null, "Use <Tab> to shift option-button, then press <Enter>. " +
                             "I'll write the returned value to sdt out.");
         System.out.println ("Returned value: " + n);
    }

    import javax.swing.*;
    class TabOptions
    public static void main (String [] args)
    UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE);//<--------------------
    int n = JOptionPane.showConfirmDialog (null, "Use <Tab> to shift option-button, then press <Enter>. " +
    "I'll write the returned value to sdt out.");
    System.out.println ("Returned value: " + n);
    }

Maybe you are looking for

  • Adobe Acrobat 9 pro prompted me to uninstall & reinstall.  I now cannot find my original CD!!

    Anyone else experienced the same thing?  Was just exporting to a .pdf from InDesign.  Never happened before and now when I contact adobe live chat they say they cannot support me! Is there any way you can install it again if you've already purchased

  • GUI Problem

    Having a problem with jRadioButtons and an action event when a button is pushed. We want to have a calculation run when the user pushes the OK button. Need to know which radion button is selected so the calculation has the right data. Here is some of

  • Using Apple TV2 without HDMI (Component)

    I know this question has been asked before but I still have yet to find a definitive answer. I also purchased a converter box, HDMI to Component, to use with my older plasma and entertainment system and it didn't work. Has anyone had luck using the A

  • Redirect standart output to file

    i want to ask how to redirect standart output to file, if i have statement like this System.out.println("hello"); i want hello not print in console but print to file thx

  • Preference to have Safari launch with previously open webpages not showing up

    In Mountalin Lion v. 10.8.2, there was supposed to be a preference to have Safari launch with previously open webpages. I have looked multiple times in the preferences for Safari and can't find this setting. Thanks so much! I have tried installing Mo