开发者

How can I dismiss one JOptionPane upon emergence of another JOptionPane in the GUI

开发者 https://www.devze.com 2023-04-13 04:49 出处:网络
As you have seen from my subject above, I would like to know how can I dismiss a JOptionPane which became irrelevant because of another JOptionPane and because the user ,for some reason, didn\'t dismi

As you have seen from my subject above,

I would like to know how can I dismiss a JOptionPane which became irrelevant because of another JOptionPane and because the user ,for some reason, didn't dismiss the first one by himself clicking ok button (for example).

I've seen some ware in other site similar question, and people suggested to do simply:

JOptionPane.getRootFrame().dispose();  

But how can I store a reference for each JOptionPane I have and to be able to dismiss only that wanted one.

Thanks

Edited:

Code example:

package Gui;

import javax.swing.JOptionPane;
import java.awt.*;

/**
 *
 * @author 
 */
public class JpanelMainView extends javax.swing.JPanel {

    /** Creates new form JpanelMainView */
    public JpanelMainView() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(149, 149, 149)
                .addComponent(jBu开发者_如何学Pythontton1)
                .addContainerGap(178, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(77, 77, 77)
                .addComponent(jButton1)
                .addContainerGap(200, Short.MAX_VALUE))
        );
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)                                         
    {                                             
       JOptionPane.showMessageDialog(this, "Board was sent for validation check\n Please wait...","Board Sent",JOptionPane.INFORMATION_MESSAGE);

       //Please note that this OptionPane is coming in my real program always after the first JoptionPane
       //I want that if I've reached the line in the code that need to show this second JoptionPane, I will first close the first JoptionPane
       //Else you will dismiss the last JoptionPane and then the first one and I don't want to give the user two JoptionPane to close, it's annoying.
       JOptionPane.showMessageDialog(this, "Set your move now please","Game started",JOptionPane.INFORMATION_MESSAGE);
    }                                        

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    // End of variables declaration                   

}


I would recommend that you

  • create a JDialog with your JOptionPane (the JOptionPane API will show you how),
  • then use a SwingWorker for whatever background task you wish to do that should be done off of the main Swing thread, the EDT,
  • Then in the SwingWorker's done() method which is called when the background task is complete, dispose of the JDialog.
  • Then the next JOptionPane will be called immediately.

For example the following code uses a Thread.sleep(3000) for a 3 second sleep to mimic a background task that takes 3 seconds. It will then close the first dialog and show the second:

   private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
      JOptionPane messagePane = new JOptionPane(
            "Board was sent for validation check\n Please wait...",
            JOptionPane.INFORMATION_MESSAGE);
      final JDialog dialog = messagePane.createDialog(this, "Board Sent");

      new SwingWorker<Void, Void>() {

         @Override
         protected Void doInBackground() throws Exception {
            // do your background processing here
            // for instance validate your board here

            // mimics a background process that takes 3 seconds
            // you would of course delete this in your actual progam
            Thread.sleep(3000); 

            return null;
         }

         // this is called when background thread above has completed.
         protected void done() {
            dialog.dispose();
         };
      }.execute();

      dialog.setVisible(true);

      JOptionPane.showMessageDialog(this, "Set your move now please",
            "Game started", JOptionPane.INFORMATION_MESSAGE);
   }


simple answer, that not possible, because only one JOptionPane can exist in current time, if you want to solve your issue, then you have to create JDialog#ModalityType(Aplications???) or JWindow then you'll able to shows JOptionPane

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ClosingFrame extends JFrame {

    private JMenuBar MenuBar = new JMenuBar();
    private JFrame frame = new JFrame();
    private static final long serialVersionUID = 1L;
    private JMenu File = new JMenu("File");
    private JMenuItem Exit = new JMenuItem("Exit");
    private JFrame frame1 = new JFrame();

    public ClosingFrame() {
        File.add(Exit);
        MenuBar.add(File);
        Exit.addActionListener(new ExitListener());
        WindowListener exitListener = new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                int confirm = JOptionPane.showOptionDialog(frame,
                        "Are You Sure to Close this Application?",
                        "Exit Confirmation", JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE, null, null, null);
                if (confirm == 0) {
                    System.exit(1);
                }
            }
        };
        frame.addWindowListener(exitListener);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setJMenuBar(MenuBar);
        frame.setPreferredSize(new Dimension(400, 300));
        frame.setLocation(100, 100);
        frame.pack();
        frame.setVisible(true);

        frame1.addWindowListener(exitListener);
        frame1.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame1.setPreferredSize(new Dimension(400, 300));
        frame1.setLocation(500, 100);
        frame1.pack();
        frame1.setVisible(true);
    }

    private class ExitListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            int confirm = JOptionPane.showOptionDialog(frame,
                    "Are You Sure to Close this Application?",
                    "Exit Confirmation", JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, null, null);
            JOptionPane.showMessageDialog(null, "Whatever", "Whatever",
                    JOptionPane.ERROR_MESSAGE);
            int confirm1 = JOptionPane.showOptionDialog(frame1,
                    "Are You Sure to Close this Application?",
                    "Exit Confirmation", JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, null, null);
            if (confirm == 0) {
                //System.exit(1);
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ClosingFrame cf = new ClosingFrame();
            }
        });
    }
}


Sorry I don't understand your question well, do you mean that you want to close one JOptionPane from another one?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class GUIProgram extends JFrame implements ActionListener
{
    private JButton btn1, btn2, btn3;
    private static final String BUTTON1_COMMAND = "Press it!";
    private static final String BUTTON2_COMMAND = "show new JOptionPane!";
    private static final String BUTTON3_COMMAND = "close old JOptionPane!";
    private JOptionPane pane1, pane2;

    public GUIProgram()
    {
        super("The title");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        btn1 = new JButton(BUTTON1_COMMAND);
        btn1.addActionListener(this);
        btn1.setActionCommand(BUTTON1_COMMAND);

        btn2 = new JButton(BUTTON2_COMMAND);
        btn2.addActionListener(this);
        btn2.setActionCommand(BUTTON2_COMMAND);

        btn3 = new JButton(BUTTON3_COMMAND);
        btn3.addActionListener(this);
        btn3.setActionCommand(BUTTON3_COMMAND);

        pane1 = new JOptionPane();
        pane2 = new JOptionPane();

        getContentPane().add(btn1);
        setSize(200, 100);
        setVisible(true);
    }

    public static void main(String args[])
    {
        new GUIProgram();
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        if(e.getActionCommand().equals(BUTTON1_COMMAND))
        {
            JPanel panel = new JPanel();
            panel.add(btn2);
            pane1.showOptionDialog(null, panel, "JOptionPane #1", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, new Object[]{}, null);
        }

        else if(e.getActionCommand().equals(BUTTON2_COMMAND))
        {
            JPanel panel = new JPanel();
            panel.add(btn3);
            pane2.showOptionDialog(null, panel, "JOptionPane #2", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, new Object[]{}, null);
        }

        else if(e.getActionCommand().equals(BUTTON3_COMMAND))
        {
            pane1.getRootFrame().dispose();
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消