Example usage for javax.swing JOptionPane showOptionDialog

List of usage examples for javax.swing JOptionPane showOptionDialog

Introduction

In this page you can find the example usage for javax.swing JOptionPane showOptionDialog.

Prototype

@SuppressWarnings("deprecation")
public static int showOptionDialog(Component parentComponent, Object message, String title, int optionType,
        int messageType, Icon icon, Object[] options, Object initialValue) throws HeadlessException 

Source Link

Document

Brings up a dialog with a specified icon, where the initial choice is determined by the initialValue parameter and the number of choices is determined by the optionType parameter.

Usage

From source file:de.adv_online.aaa.katalogtool.KatalogDialog.java

public void initialise(Converter c, Options o, ShapeChangeResult r, String mdl)
        throws ShapeChangeAbortException {

    try {//from   ww  w. j ava2  s .  c o m
        String msg = "Akzeptieren Sie die in der mit diesem Tool ausgelieferten Datei 'Lizenzbedingungen zur Nutzung von Softwareskripten.doc' beschriebenen Lizenzbedingungen?"; // Meldung
        if (msg != null) {
            Object[] options = { "Ja", "Nein" };
            int val = JOptionPane.showOptionDialog(null, msg, "Confirmation", JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
            if (val == 1)
                System.exit(0);
        }
    } catch (Exception e) {
        System.out.println("Fehler in Dialog: " + e.toString());
    }

    options = o;

    File eapFile = new File(mdl);
    try {
        eap = eapFile.getCanonicalFile().getAbsolutePath();
    } catch (IOException e) {
        eap = "ERROR.eap";
    }

    converter = new Converter(options, r);
    result = r;
    modelTransformed = false;
    transformationRunning = false;

    StatusBoard.getStatusBoard().registerStatusReader(this);

    // frame
    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

    // panel
    newContentPane = new JPanel(new BorderLayout());
    newContentPane.setOpaque(true);
    setContentPane(newContentPane);

    // target elements
    for (String label : targetLabels) {
        try {
            TargetGuiElements t = new TargetGuiElements(this, label);
            targetGuiElems.put(label, t);
        } catch (Exception e) {
            throw new ShapeChangeAbortException("Fatal error while creating dialog elements for target " + label
                    + ".\nMessage: " + eap.toString() + "\nPlease check configuration file.");
        }
    }

    //JTabbedPane tabbedPane = new JTabbedPane();
    //tabbedPane.addTab("Main options", createMainTab());

    newContentPane.add(createMainTab(), BorderLayout.CENTER);

    statusBar = new StatusBar();

    Box fileBox = Box.createVerticalBox();
    fileBox.add(createStartPanel());
    fileBox.add(statusBar);

    newContentPane.add(fileBox, BorderLayout.SOUTH);

    // frame size
    int height = 720;
    int width = 600;

    pack();

    Insets fI = getInsets();
    setSize(width + fI.right + fI.left, height + fI.top + fI.bottom);
    Dimension sD = Toolkit.getDefaultToolkit().getScreenSize();
    setLocation((sD.width - width) / 2, (sD.height - height) / 2);
    this.setMinimumSize(new Dimension(width, height));

    // frame closing
    WindowListener listener = new WindowAdapter() {
        public void windowClosing(WindowEvent w) {
            //JOptionPane.showMessageDialog(null, "Nein", "NO", JOptionPane.ERROR_MESSAGE);
            closeDialog();
        }
    };
    addWindowListener(listener);
}

From source file:sim.util.media.chart.ChartGenerator.java

/** Stops a Quicktime movie and cleans up, flushing the remaining frames out to disk. 
This method ought to be called from the main event loop. */
public void stopMovie() {
    if (movieMaker == null)
        return; // already stopped
    if (!movieMaker.stop()) {
        Object[] options = { "Drat" };
        JOptionPane.showOptionDialog(this,
                "Your movie did not write to disk\ndue to a spurious JMF movie generation bug.",
                "JMF Movie Generation Bug", JOptionPane.OK_OPTION, JOptionPane.WARNING_MESSAGE, null, options,
                options[0]);//from w  w  w .  j  a v a2  s.  c o  m
    }
    movieMaker = null;
    if (movieButton != null) // hasn't been destroyed yet
    {
        movieButton.setText("Create Movie");
    }
}

From source file:kevin.gvmsgarch.App.java

private static ContactFilter buildFilter() {
    ContactFilter retval = null;//from  w ww .ja v  a 2 s .  c om

    int optionPaneResult;

    //        optionPaneResult = JOptionPane.showConfirmDialog(null, "Do you want to enable filtering?", "", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
    String[] options = new String[] { "Yes", "No" };

    optionPaneResult = JOptionPane.showOptionDialog(null, "Do you want to enable filtering?", "",
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);

    if (optionPaneResult == 0) {
        JOptionPane.showMessageDialog(null, filterExplanation);
        String contactName = JOptionPane
                .showInputDialog("Filter String (contact display name or phone number)");
        if (contactName == null || contactName.trim().isEmpty()) {
            retval = new NullFilter();
        } else {
            if (contactName.trim().equals("Unknown")) {
                retval = new UnknownFilter();
            } else {
                retval = new NameNumberFilter(contactName);
            }
        }
    } else if (optionPaneResult == JOptionPane.NO_OPTION) {
        retval = new NullFilter();

    }

    return retval;
}

From source file:com.esp8266.mkspiffs.ESP8266FS.java

private void createAndUpload() {
    if (!PreferencesData.get("target_platform").contentEquals("esp8266")) {
        System.err.println();/*from  w  w w. j a va  2s. c om*/
        editor.statusError("SPIFFS Not Supported on " + PreferencesData.get("target_platform"));
        return;
    }

    if (!BaseNoGui.getBoardPreferences().containsKey("build.spiffs_start")
            || !BaseNoGui.getBoardPreferences().containsKey("build.spiffs_end")) {
        System.err.println();
        editor.statusError("SPIFFS Not Defined for " + BaseNoGui.getBoardPreferences().get("name"));
        return;
    }
    long spiStart, spiEnd, spiPage, spiBlock;
    try {
        spiStart = getIntPref("build.spiffs_start");
        spiEnd = getIntPref("build.spiffs_end");
        spiPage = getIntPref("build.spiffs_pagesize");
        if (spiPage == 0)
            spiPage = 256;
        spiBlock = getIntPref("build.spiffs_blocksize");
        if (spiBlock == 0)
            spiBlock = 4096;
    } catch (Exception e) {
        editor.statusError(e);
        return;
    }

    TargetPlatform platform = BaseNoGui.getTargetPlatform();

    //Make sure mkspiffs binary exists
    String mkspiffsCmd;
    if (PreferencesData.get("runtime.os").contentEquals("windows"))
        mkspiffsCmd = "mkspiffs.exe";
    else
        mkspiffsCmd = "mkspiffs";

    File tool = new File(platform.getFolder() + "/tools", mkspiffsCmd);
    if (!tool.exists() || !tool.isFile()) {
        tool = new File(platform.getFolder() + "/tools/mkspiffs", mkspiffsCmd);
        if (!tool.exists()) {
            tool = new File(PreferencesData.get("runtime.tools.mkspiffs.path"), mkspiffsCmd);
            if (!tool.exists()) {
                System.err.println();
                editor.statusError("SPIFFS Error: mkspiffs not found!");
                return;
            }
        }
    }

    Boolean isNetwork = false;
    File espota = new File(platform.getFolder() + "/tools");
    File esptool = new File(platform.getFolder() + "/tools");
    String serialPort = PreferencesData.get("serial.port");

    //make sure the serial port or IP is defined
    if (serialPort == null || serialPort.isEmpty()) {
        System.err.println();
        editor.statusError("SPIFFS Error: serial port not defined!");
        return;
    }

    //find espota if IP else find esptool
    if (serialPort.split("\\.").length == 4) {
        isNetwork = true;
        String espotaCmd = "espota.py";
        espota = new File(platform.getFolder() + "/tools", espotaCmd);
        if (!espota.exists() || !espota.isFile()) {
            System.err.println();
            editor.statusError("SPIFFS Error: espota not found!");
            return;
        }
    } else {
        String esptoolCmd = platform.getTool("esptool").get("cmd");
        esptool = new File(platform.getFolder() + "/tools", esptoolCmd);
        if (!esptool.exists() || !esptool.isFile()) {
            esptool = new File(platform.getFolder() + "/tools/esptool", esptoolCmd);
            if (!esptool.exists()) {
                esptool = new File(PreferencesData.get("runtime.tools.esptool.path"), esptoolCmd);
                if (!esptool.exists()) {
                    System.err.println();
                    editor.statusError("SPIFFS Error: esptool not found!");
                    return;
                }
            }
        }
    }

    //load a list of all files
    int fileCount = 0;
    File dataFolder = new File(editor.getSketch().getFolder(), "data");
    if (!dataFolder.exists()) {
        dataFolder.mkdirs();
    }
    if (dataFolder.exists() && dataFolder.isDirectory()) {
        File[] files = dataFolder.listFiles();
        if (files.length > 0) {
            for (File file : files) {
                if ((file.isDirectory() || file.isFile()) && !file.getName().startsWith("."))
                    fileCount++;
            }
        }
    }

    String dataPath = dataFolder.getAbsolutePath();
    String toolPath = tool.getAbsolutePath();
    String sketchName = editor.getSketch().getName();
    String imagePath = getBuildFolderPath(editor.getSketch()) + "\\" + sketchName + ".spiffs.bin";
    String resetMethod = BaseNoGui.getBoardPreferences().get("upload.resetmethod");
    String uploadSpeed = BaseNoGui.getBoardPreferences().get("upload.speed");
    String uploadAddress = BaseNoGui.getBoardPreferences().get("build.spiffs_start");

    Object[] options = { "Yes", "No" };
    String title = "SPIFFS Create";
    String message = "No files have been found in your data folder!\nAre you sure you want to create an empty SPIFFS image?";

    if (fileCount == 0 && JOptionPane.showOptionDialog(editor, message, title, JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, options, options[1]) != JOptionPane.YES_OPTION) {
        System.err.println();
        editor.statusError("SPIFFS Warning: mkspiffs canceled!");
        return;
    }

    editor.statusNotice("SPIFFS Creating Image...");
    System.out.println("[SPIFFS] data   : " + dataPath);
    System.out.println("[SPIFFS] size   : " + ((spiEnd - spiStart) / 1024));
    System.out.println("[SPIFFS] page   : " + spiPage);
    System.out.println("[SPIFFS] block  : " + spiBlock);

    try {
        if (listenOnProcess(new String[] { toolPath, "-c", dataPath, "-p", spiPage + "", "-b", spiBlock + "",
                "-s", (spiEnd - spiStart) + "", imagePath }) != 0) {
            System.err.println();
            editor.statusError("SPIFFS Create Failed!");
            return;
        }
    } catch (Exception e) {
        editor.statusError(e);
        editor.statusError("SPIFFS Create Failed!");
        return;
    }

    title = "SPIFFS Copy";
    message = "Would you like a copy of the SPIFFS image in your project folder?";

    if (JOptionPane.showOptionDialog(editor, message, title, JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, options, options[0]) == JOptionPane.YES_OPTION) {
        File source = new File(imagePath);
        File dest = new File(editor.getSketch().getFolder(), "\\" + sketchName + ".spiffs.bin");
        try {
            Files.copy(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
            System.out.println("Copied SPIFFS image");
        } catch (IOException e) {
            System.out.println(e);
            editor.statusError("Copy SPIFFS image failed");
        }
    }

    editor.statusNotice("SPIFFS Uploading Image...");
    System.out.println("[SPIFFS] upload : " + imagePath);

    if (isNetwork) {
        String pythonCmd;
        if (PreferencesData.get("runtime.os").contentEquals("windows"))
            pythonCmd = "python.exe";
        else
            pythonCmd = "python";

        System.out.println("[SPIFFS] IP     : " + serialPort);
        System.out.println();
        sysExec(new String[] { pythonCmd, espota.getAbsolutePath(), "-i", serialPort, "-s", "-f", imagePath });
    } else {
        System.out.println("[SPIFFS] address: " + uploadAddress);
        System.out.println("[SPIFFS] reset  : " + resetMethod);
        System.out.println("[SPIFFS] port   : " + serialPort);
        System.out.println("[SPIFFS] speed  : " + uploadSpeed);
        System.out.println();
        sysExec(new String[] { esptool.getAbsolutePath(), "-cd", resetMethod, "-cb", uploadSpeed, "-cp",
                serialPort, "-ca", uploadAddress, "-cf", imagePath });
    }
}

From source file:com.qframework.core.GameonApp.java

private void onTextInput(final String resptype, final String respdata) {

    Timer t = new javax.swing.Timer(50, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JTextField area = new JTextField(resptype);
            area.setFocusable(true);/*from   ww w  . j  ava2  s . c o m*/
            area.requestFocus();
            Object options[] = new Object[] { area };
            Frame parent = null;
            if (mAppContext != null)
                parent = (Frame) SwingUtilities.getAncestorOfClass(java.awt.Frame.class, mAppContext);
            else
                parent = (Frame) SwingUtilities.getAncestorOfClass(java.awt.Frame.class, mAppletContext);

            int option = JOptionPane.showOptionDialog(parent, options, "", JOptionPane.YES_OPTION,
                    JOptionPane.INFORMATION_MESSAGE, null, null, null);
            if (option == JOptionPane.YES_OPTION) {
                String truncated = area.getText().replaceAll("[^A-Za-z0-9:.@ ]", "");
                String script = respdata + "('" + truncated + "' , 1);";
                mScript.execScript(script);
            } else {
                String script = respdata + "(undefined, 1);";
                mScript.execScript(script);

            }
        }
    });
    t.setRepeats(false);
    t.start();

}

From source file:edu.gmu.cs.sim.util.media.chart.ChartGenerator.java

/** Stops a Quicktime movie and cleans up, flushing the remaining frames out to disk.
 This method ought to be called from the main event loop. */
public void stopMovie() {
    if (movieMaker == null) {
        return; // already stopped
    }/*from   ww w . j a v  a  2 s .  c om*/
    if (!movieMaker.stop()) {
        Object[] options = { "Drat" };
        JOptionPane.showOptionDialog(this,
                "Your movie did not write to disk\ndue to a spurious JMF movie generation bug.",
                "JMF Movie Generation Bug", JOptionPane.OK_OPTION, JOptionPane.WARNING_MESSAGE, null, options,
                options[0]);
    }
    movieMaker = null;
    if (movieButton != null) // hasn't been destroyed yet
    {
        movieButton.setText("Create Movie");
    }
}

From source file:gov.nih.nci.nbia.StandaloneDMDispatcher.java

private void constructDownloadPanelWithOption(String downloadUrl, Object[] options) {
    String nVMsg = newVersionMsg;
    if (os.equalsIgnoreCase("CentOS") || os.equalsIgnoreCase("Ubuntu")) {
        nVMsg = nVMsg + "\nIf choosing Update automatically, you need to enter a sudo password later.";
    }//from   w  ww .  j  a  v a 2 s .c om

    if (os.startsWith("mac")) {
        JOptionPane.showMessageDialog(null, "New version is available on App Store. Please upgrade.");
        if (options.length == 2) { // forced upgrade needed
            System.exit(1);
        } else {
            nogo = false;
            return;
        }
    }

    int n = JOptionPane.showOptionDialog(null, nVMsg, "New Version Notification",
            JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);

    if (n == 0) {
        saveAndInstall(downloadUrl);
        nogo = true;
    } else if (n == 1) {
        try {
            saveFile(downloadUrl);
            nogo = false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else if (n == 2) {
        nogo = false;
    }
}

From source file:de.lazyzero.kkMulticopterFlashTool.KKMulticopterFlashTool.java

private void checkVersion() {
    logger.log(Level.INFO, "Check the version: " + VERSION + (isBeta ? " beta " + betaVersion : "")
            + " online is version: " + firmwareReader.getActualVersion());
    if (firmwareReader.getActualVersion() > Double.parseDouble(VERSION)) {
        //         JOptionPane.showMessageDialog(this, _("update"));
        String[] choices = { _("downloads.download"), _("Cancel") };
        int result = JOptionPane.showOptionDialog(this, _("update"), "", JOptionPane.YES_NO_CANCEL_OPTION,
                JOptionPane.INFORMATION_MESSAGE, null, choices, choices[0]);
        if (result == 0) {
            kkMenu.openURL("http://kkflashtool.de");
            System.exit(0);//w  w  w  . j a v a  2 s .  c o m
        }
    }
}

From source file:fr.vdl.android.holocolors.HoloColorsDialog.java

private void unzipFile(File zipFile) throws Exception {
    File outputFolder = new File(resPathTextField.getText());

    boolean overwriteAll = false;
    boolean overwriteNone = false;
    Object[] overwriteOptions = { "Overwrite this file", "Overwrite all", "Do not overwrite this file",
            "Do not overwrite any file" };

    ZipInputStream zis = null;/* w ww . j  a va2 s.  c o m*/
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    try {
        zis = new ZipInputStream(new FileInputStream(zipFile));
        ZipEntry ze = zis.getNextEntry();
        while (ze != null) {
            String fileName = ze.getName().replaceFirst("res/", "");
            File newFile = new File(outputFolder + File.separator + fileName);

            new File(newFile.getParent()).mkdirs();

            boolean overwrite = overwriteAll || (!newFile.exists());
            if (newFile.exists() && newFile.isFile() && !overwriteAll && !overwriteNone) {
                int option = JOptionPane.showOptionDialog(ahcPanel,
                        newFile.getName() + " already exists, overwrite ?", "File exists",
                        JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
                        new ImageIcon(getClass().getResource("/icons/H64.png")), overwriteOptions,
                        overwriteOptions[0]);

                switch (option) {
                case 0:
                    overwrite = true;
                    break;
                case 1:
                    overwrite = true;
                    overwriteAll = true;
                    break;
                case 2:
                    overwrite = false;
                    break;
                case 3:
                    overwrite = false;
                    overwriteNone = true;
                    break;
                default:
                    overwrite = false;
                }
            }

            if (overwrite && !fileName.endsWith(File.separator)) {
                FileOutputStream fos = new FileOutputStream(newFile);
                int len;
                while ((len = zis.read(buffer)) > 0) {
                    fos.write(buffer, 0, len);
                }
                fos.close();
            }
            ze = zis.getNextEntry();
        }

        zis.closeEntry();
        zis.close();
    } finally {
        if (zis != null) {
            try {
                zis.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:edu.ku.brc.specify.dbsupport.TaskSemaphoreMgr.java

/**
 * @param title//from   w ww.jav  a 2 s .  c  om
 * @param name
 * @param scope
 * @return
 */
public static boolean askUserToUnlock(final String title, final String name, final SCOPE scope) {
    SpecifyUser user = AppContextMgr.getInstance().getClassObject(SpecifyUser.class);
    Discipline discipline = scope == SCOPE.Discipline
            ? AppContextMgr.getInstance().getClassObject(Discipline.class)
            : null;
    Collection collection = scope == SCOPE.Collection
            ? AppContextMgr.getInstance().getClassObject(Collection.class)
            : null;

    DataProviderSessionIFace session = null;
    try {
        session = DataProviderFactory.getInstance().createSession();

        SpTaskSemaphore semaphore = null;
        try {
            semaphore = getSemaphore(session, name, scope, discipline, collection);

        } catch (StaleObjectException ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(TaskSemaphoreMgr.class, ex);
            semaphore = null;
        }

        if (semaphore == null) {
            // can't be unlocked at this time.
            // or it isn't locked

        } else {
            if (!semaphore.getIsLocked()
                    && !(semaphore.getUsageCount() != null && semaphore.getUsageCount() > 0)) {
                return false;
            }

            // Check to see if we have the same user on the same machine.
            String currMachineName = InetAddress.getLocalHost().toString();
            String dbMachineName = semaphore.getMachineName();

            if (StringUtils.isNotEmpty(dbMachineName) && StringUtils.isNotEmpty(currMachineName)
                    && currMachineName.equals(dbMachineName) && semaphore.getOwner() != null && user != null
                    && user.getId().equals(semaphore.getOwner().getId())) {
                // In use by this user

                int options = JOptionPane.YES_NO_OPTION;
                Object[] optionLabels = new String[] { getResourceString("SpTaskSemaphore.OVERRIDE"), //$NON-NLS-1$
                        getResourceString("CANCEL")//$NON-NLS-1$
                };
                int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(),
                        getLocalizedMessage("SpTaskSemaphore.IN_USE_BY_YOU_UNLK", title, title),
                        getResourceString("SpTaskSemaphore.IN_USE_TITLE"), //$NON-NLS-1$
                        options, JOptionPane.QUESTION_MESSAGE, null, optionLabels, 1);

                return userChoice == JOptionPane.YES_OPTION;
            }

            String userStr = prevLockedBy != null ? prevLockedBy : semaphore.getOwner().getIdentityTitle();
            String msg = UIRegistry.getLocalizedMessage("SpTaskSemaphore.IN_USE_OV_UNLK", title, userStr,
                    semaphore.getLockedTime() == null ? "?" : semaphore.getLockedTime().toString());

            int options;
            Object[] optionLabels;
            options = JOptionPane.YES_NO_OPTION;
            optionLabels = new String[] { getResourceString("SpTaskSemaphore.OVERRIDE"), //$NON-NLS-1$
                    getResourceString("CANCEL"), //$NON-NLS-1$
            };

            int userChoice = JOptionPane.showOptionDialog(UIRegistry.getTopWindow(), msg,
                    getResourceString("SpTaskSemaphore.IN_USE_TITLE"), //$NON-NLS-1$
                    options, JOptionPane.QUESTION_MESSAGE, null, optionLabels, 1);
            return userChoice == JOptionPane.YES_OPTION;
        }

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(TaskSemaphoreMgr.class, ex);
        ex.printStackTrace();
        //log.error(ex);

    } finally {
        if (session != null) {
            session.close();
        }
    }

    return false;
}