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:Main.java

public static int select(String[] selList, String msg) {
    JComboBox<String> box = new JComboBox<>(selList);
    Object msgs[] = new Object[2];
    msgs[0] = msg;/* w w w.j  a v  a  2s  .  c  o m*/
    msgs[1] = box;
    int result = JOptionPane.showOptionDialog(null, msgs, msg, JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, null, null);
    if (result == JOptionPane.CANCEL_OPTION)
        return -1;
    return box.getSelectedIndex();
}

From source file:Main.java

public Main() {
    setSize(200, 200);/*from w  w w.j av  a2s.  co  m*/
    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent evt) {
            Object[] options = { "Quit, My Computing Fellow", "No, I want to Work more" };

            int answer = JOptionPane.showOptionDialog(Main.this, "What would you like to do? ", "Quit:Continue",
                    JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
            if (answer == JOptionPane.YES_OPTION) {
                System.exit(0);
            }
        }
    });
}

From source file:Main.java

/**
 * Shows a simple yes/no confirmation dialog, with the "no" option selected by default. This method exists
 * only because there's apparently no easy way to accomplish that with JOptionPane's static helper
 * methods.//w ww  .j  a  v  a 2  s. com
 * 
 * @param parentComponent
 * @param message
 * @param title
 * @see JOptionPane#showConfirmDialog(Component, Object, String, int)
 */
public static int showConfirmDialog(Component parentComponent, Object message, String title) {
    String[] options = { "Yes", "No" };
    return JOptionPane.showOptionDialog(parentComponent, message, title, JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
}

From source file:Main.java

/**Prompt the user to choose between two courses of action.
 @return true if the user chose the default course of action,
   false if the alternate course was chosen of the prompt closed.*/
public static boolean prompt2(Component parent, String question, String title, String defaultActionText,
        String alternateActionText) {
    Object[] values = new Object[] { defaultActionText, alternateActionText };

    int choice = JOptionPane.showOptionDialog(parent, question, title, JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, values, values[0]);

    return choice == JOptionPane.YES_OPTION;
}

From source file:au.com.jwatmuff.eventmanager.Main.java

/**
 * Main method.//from  w  ww  . j  av a2  s . c  om
 */
public static void main(String args[]) {
    LogUtils.setupUncaughtExceptionHandler();

    /* Set timeout for RMI connections - TODO: move to external file */
    System.setProperty("sun.rmi.transport.tcp.handshakeTimeout", "2000");
    updateRmiHostName();

    /*
     * Set up menu bar for Mac
     */
    System.setProperty("apple.laf.useScreenMenuBar", "true");
    System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Event Manager");

    /*
     * Set look and feel to 'system' style
     */
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        log.info("Failed to set system look and feel");
    }

    /*
     * Set workingDir to a writable folder for storing competitions, settings etc.
     */
    String applicationData = System.getenv("APPDATA");
    if (applicationData != null) {
        workingDir = new File(applicationData, "EventManager");
        if (workingDir.exists() || workingDir.mkdirs()) {
            // redirect logging to writable folder
            LogUtils.reconfigureFileAppenders("log4j.properties", workingDir);
        } else {
            workingDir = new File(".");
        }
    }

    // log version for debugging
    log.info("Running version: " + VISIBLE_VERSION + " (Internal: " + VERSION + ")");

    /*
     * Copy license if necessary
     */
    File license1 = new File("license.lic");
    File license2 = new File(workingDir, "license.lic");
    if (license1.exists() && !license2.exists()) {
        try {
            FileUtils.copyFile(license1, license2);
        } catch (IOException e) {
            log.warn("Failed to copy license from " + license1 + " to " + license2, e);
        }
    }
    if (license1.exists() && license2.exists()) {
        if (license1.lastModified() > license2.lastModified()) {
            try {
                FileUtils.copyFile(license1, license2);
            } catch (IOException e) {
                log.warn("Failed to copy license from " + license1 + " to " + license2, e);
            }
        }
    }

    /*
     * Check if run lock exists, if so ask user if it is ok to continue
     */
    if (!obtainRunLock(false)) {
        int response = JOptionPane.showConfirmDialog(null,
                "Unable to obtain run-lock.\nPlease ensure that no other instances of EventManager are running before continuing.\nDo you wish to continue?",
                "Run-lock detected", JOptionPane.YES_NO_OPTION);
        if (response == JOptionPane.YES_OPTION)
            obtainRunLock(true);
        else
            System.exit(0);
    }

    try {
        LoadWindow loadWindow = new LoadWindow();
        loadWindow.setVisible(true);

        loadWindow.addMessage("Reading settings..");

        /*
         * Read properties from file
         */
        final Properties props = new Properties();
        try {
            Properties defaultProps = PropertiesLoaderUtils
                    .loadProperties(new ClassPathResource("eventmanager.properties"));
            props.putAll(defaultProps);
        } catch (IOException ex) {
            log.error(ex);
        }

        props.putAll(System.getProperties());

        File databaseStore = new File(workingDir, "comps");
        int rmiPort = Integer.parseInt(props.getProperty("eventmanager.rmi.port"));

        loadWindow.addMessage("Loading Peer Manager..");
        log.info("Loading Peer Manager");

        ManualDiscoveryService manualDiscoveryService = new ManualDiscoveryService();
        JmDNSRMIPeerManager peerManager = new JmDNSRMIPeerManager(rmiPort, new File(workingDir, "peerid.dat"));
        peerManager.addDiscoveryService(manualDiscoveryService);

        monitorNetworkInterfaceChanges(peerManager);

        loadWindow.addMessage("Loading Database Manager..");
        log.info("Loading Database Manager");

        DatabaseManager databaseManager = new SQLiteDatabaseManager(databaseStore, peerManager);
        LicenseManager licenseManager = new LicenseManager(workingDir);

        loadWindow.addMessage("Loading Load Competition Dialog..");
        log.info("Loading Load Competition Dialog");

        LoadCompetitionWindow loadCompetitionWindow = new LoadCompetitionWindow(databaseManager, licenseManager,
                peerManager);
        loadCompetitionWindow.setTitle(WINDOW_TITLE);

        loadWindow.dispose();
        log.info("Starting Load Competition Dialog");

        while (true) {
            // reset permission checker to use our license
            licenseManager.updatePermissionChecker();

            GUIUtils.runModalJFrame(loadCompetitionWindow);

            if (loadCompetitionWindow.getSuccess()) {
                DatabaseInfo info = loadCompetitionWindow.getSelectedDatabaseInfo();

                if (!databaseManager.checkLock(info.id)) {
                    String message = "EventManager did not shut down correctly the last time this competition was open. To avoid potential data corruption, you are advised to take the following steps:\n"
                            + "1) Do NOT open this competition\n" + "2) Create a backup of this competition\n"
                            + "3) Delete the competition from this computer\n"
                            + "4) If possible, reload this competition from another computer on the network\n"
                            + "5) Alternatively, you may manually load the backup onto all computers on the network, ensuring the 'Preserve competition ID' option is checked.";
                    String title = "WARNING: Potential Data Corruption Detected";

                    int status = JOptionPane.showOptionDialog(null, message, title, JOptionPane.YES_NO_OPTION,
                            JOptionPane.ERROR_MESSAGE, null,
                            new Object[] { "Cancel (recommended)", "Open anyway" }, "Cancel (recommended)");

                    if (status == 0)
                        continue; // return to load competition window
                }

                SynchronizingWindow syncWindow = new SynchronizingWindow();
                syncWindow.setVisible(true);
                long t = System.nanoTime();
                DistributedDatabase database = databaseManager.activateDatabase(info.id, info.passwordHash);
                long dt = System.nanoTime() - t;
                log.debug(String.format("Initial sync in %dms",
                        TimeUnit.MILLISECONDS.convert(dt, TimeUnit.NANOSECONDS)));
                syncWindow.dispose();

                if (loadCompetitionWindow.isNewDatabase()) {
                    GregorianCalendar calendar = new GregorianCalendar();
                    Date today = calendar.getTime();
                    calendar.set(Calendar.MONTH, Calendar.DECEMBER);
                    calendar.set(Calendar.DAY_OF_MONTH, 31);
                    Date endOfYear = new java.sql.Date(calendar.getTimeInMillis());

                    CompetitionInfo ci = new CompetitionInfo();
                    ci.setName(info.name);
                    ci.setStartDate(today);
                    ci.setEndDate(today);
                    ci.setAgeThresholdDate(endOfYear);
                    //ci.setPasswordHash(info.passwordHash);
                    License license = licenseManager.getLicense();
                    if (license != null) {
                        ci.setLicenseName(license.getName());
                        ci.setLicenseType(license.getType().toString());
                        ci.setLicenseContact(license.getContactPhoneNumber());
                    }
                    database.add(ci);
                }

                // Set PermissionChecker to use database's license type
                String competitionLicenseType = database.get(CompetitionInfo.class, null).getLicenseType();
                PermissionChecker.setLicenseType(LicenseType.valueOf(competitionLicenseType));

                TransactionNotifier notifier = new TransactionNotifier();
                database.setListener(notifier);

                MainWindow mainWindow = new MainWindow();
                mainWindow.setDatabase(database);
                mainWindow.setNotifier(notifier);
                mainWindow.setPeerManager(peerManager);
                mainWindow.setLicenseManager(licenseManager);
                mainWindow.setManualDiscoveryService(manualDiscoveryService);
                mainWindow.setTitle(WINDOW_TITLE);
                mainWindow.afterPropertiesSet();

                TestUtil.setActivatedDatabase(database);

                // show main window (modally)
                GUIUtils.runModalJFrame(mainWindow);

                // shutdown procedures

                // System.exit();

                database.shutdown();
                databaseManager.deactivateDatabase(1500);

                if (mainWindow.getDeleteOnExit()) {
                    for (File file : info.localDirectory.listFiles())
                        if (!file.isDirectory())
                            file.delete();
                    info.localDirectory.deleteOnExit();
                }
            } else {
                // This can cause an RuntimeException - Peer is disconnected
                peerManager.stop();
                System.exit(0);
            }
        }
    } catch (Throwable e) {
        log.error("Error in main function", e);
        String message = e.getMessage();
        if (message == null)
            message = "";
        if (message.length() > 100)
            message = message.substring(0, 97) + "...";
        GUIUtils.displayError(null,
                "An unexpected error has occured.\n\n" + e.getClass().getSimpleName() + "\n" + message);
        System.exit(0);
    }
}

From source file:Main.java

protected static void errorMessage(String errorMessage) {

    /**/*from  w w  w. j ava 2  s. c  om*/
     * Display Jpanel Error messages any text Errors. Overloads
     * errorMessage(Exception exceptionMsg)
     */
    Object[] options = { "OK" };

    JOptionPane.showOptionDialog(null, errorMessage, messagerHeader, JOptionPane.DEFAULT_OPTION,
            JOptionPane.WARNING_MESSAGE, null, options, options[0]);

    // DatabaseManagerSwing.StatusMessage(READY_STATUS);
}

From source file:minecrunch_updater.Minecrunch_updater.java

private static void VersionCheck() throws MalformedURLException {

    // Get system properties
    String os = System.getProperty("os.name");
    String home = System.getProperty("user.home");
    String dir;//from ww w. j a  v a 2s .c o m
    String newfile2 = null;

    if (os.contains("Windows")) {
        dir = home + "\\.minecrunch\\";
        newfile2 = dir + "\\resources\\";
    } else {
        dir = home + "/.minecrunch/";
        newfile2 = dir + "/resources/";
    }

    try {
        // Get version.txt from server
        URL url = new URL("http://www.minecrunch.net/download/minecrunch_installer/version.txt");
        File file = new File(dir + "version.txt");
        File file2 = new File(newfile2 + "version.txt");

        FileUtils.copyURLToFile(url, file);
        boolean isTwoEqual = FileUtils.contentEquals(file, file2);

        if (isTwoEqual) {
            System.out.println("Up to date.");
            Run();
        } else {
            Object[] options = { "Yes, please", "No way!" };
            Component frame = null;
            // Get answer if the user wants to update or not
            int n = JOptionPane.showOptionDialog(frame, "There is an update to Minecrunch Modpack.",
                    "Would you like to update now?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
                    null, options, options[0]);

            if (n == JOptionPane.YES_OPTION) {
                // If yes run the Update method
                Update();
            } else {
                // If user chooses no then just run the minecrunch_launcher jar file
                Run();
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(Minecrunch_updater.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Main.java

public static void errorMessage(Exception exceptionMsg, boolean quiet) {

    /**//from w w  w  .j a va 2s. com
     * Display Jpanel Error messages any SQL Errors. Overloads
     * errorMessage(String e)
     */
    Object[] options = { "OK", };

    JOptionPane.showOptionDialog(null, exceptionMsg, messagerHeader, JOptionPane.DEFAULT_OPTION,
            JOptionPane.ERROR_MESSAGE, null, options, options[0]);

    if (!quiet) {
        exceptionMsg.printStackTrace();
    }

    // DatabaseManagerSwing.StatusMessage(READY_STATUS);
}

From source file:net.pms.newgui.Wizard.java

public static void run(final PmsConfiguration configuration) {
    // Total number of questions
    int numberOfQuestions = Platform.isMac() ? 4 : 5;

    // The current question number
    int currentQuestionNumber = 1;

    String status = new StringBuilder().append(Messages.getString("Wizard.2")).append(" %d ")
            .append(Messages.getString("Wizard.4")).append(" ").append(numberOfQuestions).toString();

    Object[] okOptions = { Messages.getString("Dialog.OK") };

    Object[] yesNoOptions = { Messages.getString("Dialog.YES"), Messages.getString("Dialog.NO") };

    Object[] networkTypeOptions = { Messages.getString("Wizard.8"), Messages.getString("Wizard.9"),
            Messages.getString("Wizard.10") };

    if (!Platform.isMac()) {
        // Ask if they want UMS to start minimized
        int whetherToStartMinimized = JOptionPane.showOptionDialog(null, Messages.getString("Wizard.3"),
                String.format(status, currentQuestionNumber++), JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE, null, yesNoOptions, yesNoOptions[1]);

        if (whetherToStartMinimized == JOptionPane.YES_OPTION) {
            configuration.setMinimized(true);
        } else if (whetherToStartMinimized == JOptionPane.NO_OPTION) {
            configuration.setMinimized(false);
        }//from w  ww.ja v a2s . c  om
    }

    // Ask if their network is wired, etc.
    int networkType = JOptionPane.showOptionDialog(null, Messages.getString("Wizard.7"),
            String.format(status, currentQuestionNumber++), JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, networkTypeOptions, networkTypeOptions[1]);

    switch (networkType) {
    case JOptionPane.YES_OPTION:
        // Wired (Gigabit)
        configuration.setMaximumBitrate("0");
        configuration.setMPEG2MainSettings("Automatic (Wired)");
        configuration.setx264ConstantRateFactor("Automatic (Wired)");
        break;
    case JOptionPane.NO_OPTION:
        // Wired (100 Megabit)
        configuration.setMaximumBitrate("90");
        configuration.setMPEG2MainSettings("Automatic (Wired)");
        configuration.setx264ConstantRateFactor("Automatic (Wired)");
        break;
    case JOptionPane.CANCEL_OPTION:
        // Wireless
        configuration.setMaximumBitrate("30");
        configuration.setMPEG2MainSettings("Automatic (Wireless)");
        configuration.setx264ConstantRateFactor("Automatic (Wireless)");
        break;
    default:
        break;
    }

    // Ask if they want to hide advanced options
    int whetherToHideAdvancedOptions = JOptionPane.showOptionDialog(null, Messages.getString("Wizard.11"),
            String.format(status, currentQuestionNumber++), JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, yesNoOptions, yesNoOptions[0]);

    if (whetherToHideAdvancedOptions == JOptionPane.YES_OPTION) {
        configuration.setHideAdvancedOptions(true);
    } else if (whetherToHideAdvancedOptions == JOptionPane.NO_OPTION) {
        configuration.setHideAdvancedOptions(false);
    }

    // Ask if they want to scan shared folders
    int whetherToScanSharedFolders = JOptionPane.showOptionDialog(null,
            Messages.getString("Wizard.IsStartupScan"), String.format(status, currentQuestionNumber++),
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, yesNoOptions, yesNoOptions[0]);

    if (whetherToScanSharedFolders == JOptionPane.YES_OPTION) {
        configuration.setScanSharedFoldersOnStartup(true);
    } else if (whetherToScanSharedFolders == JOptionPane.NO_OPTION) {
        configuration.setScanSharedFoldersOnStartup(false);
    }

    // Ask to set at least one shared folder
    JOptionPane.showOptionDialog(null, Messages.getString("Wizard.12"),
            String.format(status, currentQuestionNumber++), JOptionPane.OK_OPTION,
            JOptionPane.INFORMATION_MESSAGE, null, okOptions, okOptions[0]);

    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                JFileChooser chooser;
                try {
                    chooser = new JFileChooser();
                } catch (Exception ee) {
                    chooser = new JFileChooser(new RestrictedFileSystemView());
                }

                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                chooser.setDialogTitle(Messages.getString("Wizard.12"));
                chooser.setMultiSelectionEnabled(false);
                if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
                    configuration.setOnlySharedDirectory(chooser.getSelectedFile().getAbsolutePath());
                } else {
                    // If the user cancels this option, the default directories will be used.
                }
            }
        });
    } catch (InterruptedException | InvocationTargetException e) {
        LOGGER.error("Error when saving folders: ", e);
    }

    // The wizard finished, do not ask them again
    configuration.setRunWizard(false);

    // Save all changes
    try {
        configuration.save();
    } catch (ConfigurationException e) {
        LOGGER.error("Error when saving changed configuration: ", e);
    }
}

From source file:ch.zhaw.parallelComputing.view.Plotter.java

/**
 * Displays a plot of the given data sets as a dialog with a save as PNG option
 * @param parent component to set the dialog relative to
 * @param title the name of the Plot and the header of the dialog
 * @param dataset1 the first data set for plotting
 * @param dataset2 the second data set for plotting
 *///w ww  .ja va  2s .  co m
public static void plotWithDialog(Component parent, String title, XYDataset dataset1, XYDataset dataset2) {
    JFreeChart chart = plot(title, dataset1, dataset2);

    ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(1024, 768));
    chartPanel.setMouseZoomable(true, false);

    String[] options = { "Print", "OK" };
    int response = JOptionPane.showOptionDialog(parent // Center in window.
            , chartPanel, title // Title in titlebar
            , JOptionPane.YES_NO_OPTION // Option type
            , JOptionPane.PLAIN_MESSAGE // messageType
            , null // Icon (none)
            , options // Button text as above.
            , "OK" // Default button
    );

    if (response == 0) {
        getPlotAsPNG(title, dataset1, dataset2);
    }
}