Example usage for javax.swing JOptionPane OK_OPTION

List of usage examples for javax.swing JOptionPane OK_OPTION

Introduction

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

Prototype

int OK_OPTION

To view the source code for javax.swing JOptionPane OK_OPTION.

Click Source Link

Document

Return value form class method if OK is chosen.

Usage

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

private void checkManifestVersion(String manifestVersion) {
    if ((manifestVersion != null) && (Double.valueOf(manifestVersion) > Double.valueOf(appVersion))) {
        Object[] options = { "OK" };
        int n = JOptionPane.showOptionDialog(null, manifestVersionNewMsg,
                "Incompatible Manifest File Version Notification", JOptionPane.OK_OPTION,
                JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
    }//from w w  w.j  av  a2 s .  co  m

    if (((manifestVersion == null) && (supportedVersion != null))
            || ((manifestVersion != null) && (supportedVersion != null)
                    && (Double.valueOf(manifestVersion) < Double.valueOf(supportedVersion)))) {
        Object[] options = { "OK" };
        int n = JOptionPane.showOptionDialog(null, manifestVersionMsg + appVersion + ".",
                "Incompatible Manifest File Version Notification", JOptionPane.OK_OPTION,
                JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
        System.exit(n);
    }
}

From source file:net.sf.jabref.external.MoveFileAction.java

@Override
public void actionPerformed(ActionEvent event) {
    int selected = editor.getSelectedRow();

    if (selected == -1) {
        return;/*from   w  w  w. jav  a  2  s .  c o  m*/
    }

    FileListEntry entry = editor.getTableModel().getEntry(selected);

    // Check if the current file exists:
    String ln = entry.link;
    boolean httpLink = ln.toLowerCase(Locale.ENGLISH).startsWith("http");
    if (httpLink) {
        // TODO: notify that this operation cannot be done on remote links
        return;
    }

    // Get an absolute path representation:
    List<String> dirs = frame.getCurrentBasePanel().getBibDatabaseContext().getFileDirectory();
    int found = -1;
    for (int i = 0; i < dirs.size(); i++) {
        if (new File(dirs.get(i)).exists()) {
            found = i;
            break;
        }
    }
    if (found < 0) {
        JOptionPane.showMessageDialog(frame, Localization.lang("File_directory_is_not_set_or_does_not_exist!"),
                MOVE_RENAME, JOptionPane.ERROR_MESSAGE);
        return;
    }
    File file = new File(ln);
    if (!file.isAbsolute()) {
        file = FileUtil.expandFilename(ln, dirs).orElse(null);
    }
    if ((file != null) && file.exists()) {
        // Ok, we found the file. Now get a new name:
        String extension = null;
        if (entry.type.isPresent()) {
            extension = "." + entry.type.get().getExtension();
        }

        File newFile = null;
        boolean repeat = true;
        while (repeat) {
            repeat = false;
            String chosenFile;
            if (toFileDir) {
                // Determine which name to suggest:
                String suggName = FileUtil
                        .createFileNameFromPattern(eEditor.getDatabase(), eEditor.getEntry(),
                                Globals.journalAbbreviationLoader, Globals.prefs)
                        .concat(entry.type.isPresent() ? "." + entry.type.get().getExtension() : "");
                CheckBoxMessage cbm = new CheckBoxMessage(Localization.lang("Move file to file directory?"),
                        Localization.lang("Rename to '%0'", suggName),
                        Globals.prefs.getBoolean(JabRefPreferences.RENAME_ON_MOVE_FILE_TO_FILE_DIR));
                int answer;
                // Only ask about renaming file if the file doesn't have the proper name already:
                if (suggName.equals(file.getName())) {
                    answer = JOptionPane.showConfirmDialog(frame,
                            Localization.lang("Move file to file directory?"), MOVE_RENAME,
                            JOptionPane.YES_NO_OPTION);
                } else {
                    answer = JOptionPane.showConfirmDialog(frame, cbm, MOVE_RENAME, JOptionPane.YES_NO_OPTION);
                }
                if (answer != JOptionPane.YES_OPTION) {
                    return;
                }
                Globals.prefs.putBoolean(JabRefPreferences.RENAME_ON_MOVE_FILE_TO_FILE_DIR, cbm.isSelected());
                StringBuilder sb = new StringBuilder(dirs.get(found));
                if (!dirs.get(found).endsWith(File.separator)) {
                    sb.append(File.separator);
                }
                if (cbm.isSelected()) {
                    // Rename:
                    sb.append(suggName);
                } else {
                    // Do not rename:
                    sb.append(file.getName());
                }
                chosenFile = sb.toString();
            } else {
                chosenFile = FileDialogs.getNewFile(frame, file, Collections.singletonList(extension),
                        JFileChooser.SAVE_DIALOG, false);
            }
            if (chosenFile == null) {
                return; // canceled
            }
            newFile = new File(chosenFile);
            // Check if the file already exists:
            if (newFile.exists() && (JOptionPane.showConfirmDialog(frame,
                    Localization.lang("'%0' exists. Overwrite file?", newFile.getName()), MOVE_RENAME,
                    JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION)) {
                if (toFileDir) {
                    return;
                } else {
                    repeat = true;
                }
            }
        }

        if (!newFile.equals(file)) {
            try {
                boolean success = file.renameTo(newFile);
                if (!success) {
                    success = FileUtil.copyFile(file, newFile, true);
                }
                if (success) {
                    // Remove the original file:
                    if (!file.delete()) {
                        LOGGER.info("Cannot delete original file");
                    }
                    // Relativise path, if possible.
                    String canPath = new File(dirs.get(found)).getCanonicalPath();
                    if (newFile.getCanonicalPath().startsWith(canPath)) {
                        if ((newFile.getCanonicalPath().length() > canPath.length()) && (newFile
                                .getCanonicalPath().charAt(canPath.length()) == File.separatorChar)) {

                            String newLink = newFile.getCanonicalPath().substring(1 + canPath.length());
                            editor.getTableModel().setEntry(selected,
                                    new FileListEntry(entry.description, newLink, entry.type));
                        } else {
                            String newLink = newFile.getCanonicalPath().substring(canPath.length());
                            editor.getTableModel().setEntry(selected,
                                    new FileListEntry(entry.description, newLink, entry.type));
                        }

                    } else {
                        String newLink = newFile.getCanonicalPath();
                        editor.getTableModel().setEntry(selected,
                                new FileListEntry(entry.description, newLink, entry.type));
                    }
                    eEditor.updateField(editor);
                    //JOptionPane.showMessageDialog(frame, Globals.lang("File moved"),
                    //        Globals.lang("Move/Rename file"), JOptionPane.INFORMATION_MESSAGE);
                    frame.output(Localization.lang("File moved"));
                } else {
                    JOptionPane.showMessageDialog(frame, Localization.lang("Move file failed"), MOVE_RENAME,
                            JOptionPane.ERROR_MESSAGE);
                }

            } catch (SecurityException | IOException ex) {
                LOGGER.warn("Could not move file", ex);
                JOptionPane.showMessageDialog(frame,
                        Localization.lang("Could not move file '%0'.", file.getAbsolutePath())
                                + ex.getMessage(),
                        MOVE_RENAME, JOptionPane.ERROR_MESSAGE);
            }

        }
    } else {
        // File doesn't exist, so we can't move it.
        JOptionPane.showMessageDialog(frame, Localization.lang("Could not find file '%0'.", entry.link),
                Localization.lang("File not found"), JOptionPane.ERROR_MESSAGE);
    }

}

From source file:de.iritgo.aktario.client.gui.UserLoginHelper.java

static private void connectAndGo(String username, String password, final UserLoginPane loginPane) {
    CommandTools.performAsync(new ConnectToServer());
    CommandTools.performAsync(new UserLogin(username, password));

    CommandTools.performAsync(new Command() {
        @Override// w  w w .  jav  a 2 s . c  om
        public void perform() {
            try {
                SwingUtilities.invokeAndWait(new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(loginPane != null ? loginPane.getPanel() : null,
                                Engine.instance().getResourceService().getString("aktario.serverNotAvailable"),
                                Engine.instance().getResourceService().getString("app.title"),
                                JOptionPane.OK_OPTION);
                    }
                });
            } catch (InterruptedException x) {
            } catch (InvocationTargetException x) {
            }

            CommandTools.performAsync(new ShowDialog("AktarioUserLoginDialog"));
        }

        @Override
        public boolean canPerform() {
            return AppContext.instance().isConnectedWithServer() == false;
        }
    });
}

From source file:com.willwinder.universalgcodesender.utils.FirmwareUtils.java

/**
 * Copy any missing files from the the jar's resources/firmware_config/ dir
 * into the settings/firmware_config dir.
 *///ww  w . j  a v  a2s .  co  m
public synchronized static void initialize() {
    System.out.println("Initializing firmware... ...");
    File firmwareConfig = new File(SettingsFactory.getSettingsDirectory(), FIRMWARE_CONFIG_DIRNAME);

    // Create directory if it's missing.
    if (!firmwareConfig.exists()) {
        firmwareConfig.mkdirs();
    }

    FileSystem fileSystem = null;

    // Copy firmware config files.
    try {
        final String dir = "/resources/firmware_config/";

        URI location = FirmwareUtils.class.getResource(dir).toURI();

        Path myPath;
        if (location.getScheme().equals("jar")) {
            try {
                // In case the filesystem already exists.
                fileSystem = FileSystems.getFileSystem(location);
            } catch (FileSystemNotFoundException e) {
                // Otherwise create the new filesystem.
                fileSystem = FileSystems.newFileSystem(location, Collections.<String, String>emptyMap());
            }

            myPath = fileSystem.getPath(dir);
        } else {
            myPath = Paths.get(location);
        }

        Stream<Path> files = Files.walk(myPath, 1);
        for (Path path : (Iterable<Path>) () -> files.iterator()) {
            System.out.println(path);
            final String name = path.getFileName().toString();
            File fwConfig = new File(firmwareConfig, name);
            if (name.endsWith(".json")) {
                boolean copyFile = !fwConfig.exists();
                ControllerSettings jarSetting = getSettingsForStream(Files.newInputStream(path));

                // If the file is outdated... ask the user (once).
                if (fwConfig.exists()) {
                    ControllerSettings current = getSettingsForStream(new FileInputStream(fwConfig));
                    boolean outOfDate = current.getVersion() < jarSetting.getVersion();
                    if (outOfDate && !userNotified && !overwriteOldFiles) {
                        int result = NarrowOptionPane.showNarrowConfirmDialog(200,
                                Localization.getString("settings.file.outOfDate.message"),
                                Localization.getString("settings.file.outOfDate.title"),
                                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        overwriteOldFiles = result == JOptionPane.OK_OPTION;
                        userNotified = true;
                    }

                    if (overwriteOldFiles) {
                        copyFile = true;
                        jarSetting.getProcessorConfigs().Custom = current.getProcessorConfigs().Custom;
                    }
                }

                // Copy file from jar to firmware_config directory.
                if (copyFile) {
                    try {
                        save(fwConfig, jarSetting);
                    } catch (IOException ex) {
                        logger.log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    } catch (Exception ex) {
        String errorMessage = String.format("%s %s", Localization.getString("settings.file.generalError"),
                ex.getLocalizedMessage());
        GUIHelpers.displayErrorDialog(errorMessage);
        logger.log(Level.SEVERE, errorMessage, ex);
    } finally {
        if (fileSystem != null) {
            try {
                fileSystem.close();
            } catch (IOException ex) {
                logger.log(Level.SEVERE, "Problem closing filesystem.", ex);
            }
        }
    }

    configFiles.clear();
    for (File f : firmwareConfig.listFiles()) {
        try {
            ControllerSettings config = new Gson().fromJson(new FileReader(f), ControllerSettings.class);
            //ConfigLoader config = new ConfigLoader(f);
            configFiles.put(config.getName(), new ConfigTuple(config, f));
        } catch (FileNotFoundException | JsonSyntaxException | JsonIOException ex) {
            GUIHelpers.displayErrorDialog("Unable to load configuration files: " + f.getAbsolutePath());
        }
    }
}

From source file:captureplugin.drivers.defaultdriver.CaptureExecute.java

/**
 * Checks the Parameters/*from   ww  w  .j a  v  a  2  s  .  c  om*/
 *
 * @return true if OK
 */
private boolean checkParams() {
    if (!mData.getUseWebUrl() && StringUtils.isBlank(mData.getProgramPath())) {
        JOptionPane.showMessageDialog(mParent,
                mLocalizer.msg("NoProgram", "Please specify Application to use!"),
                mLocalizer.msg("CapturePlugin", "Capture Plugin"), JOptionPane.OK_OPTION);
        createDialog().show(DefaultKonfigurator.TAB_PATH);
        return false;
    }
    if (mData.getUseWebUrl() && StringUtils.isBlank(mData.getWebUrl())) {
        JOptionPane.showMessageDialog(mParent, mLocalizer.msg("NoUrl", "Please specify URL to use!"),
                mLocalizer.msg("CapturePlugin", "Capture Plugin"), JOptionPane.OK_OPTION);
        createDialog().show(DefaultKonfigurator.TAB_PATH);
        return false;
    }
    return true;
}

From source file:coolmap.canvas.datarenderer.renderer.impl.NumberComposite.java

public NumberComposite() {

    setName("Number to Composite");
    //        System.out.println("Created a new NumberComposite");
    setDescription("A renderer that can be used to assign renderers to different aggregations");

    configUI.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;//from w  ww.  ja v a 2 s. c  o  m
    c.gridy = 0;
    c.ipadx = 5;
    c.ipady = 5;
    c.insets = new Insets(2, 2, 2, 2);
    c.gridwidth = 1;

    //This combo box will need to be able to add registered
    singleComboBox = new JComboBox();
    rowComboBox = new JComboBox();
    columnComboBox = new JComboBox();
    rowColumnComboBox = new JComboBox();

    singleLegend = new JLabel();
    rowLegend = new JLabel();
    columnLegend = new JLabel();
    rowColumnLegend = new JLabel();

    singleLegend.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
    rowLegend.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
    columnLegend.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
    rowColumnLegend.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));

    //Add them
    JLabel label = new JLabel("Default:");
    label.setToolTipText("Default renderer");
    c.gridx = 0;
    c.gridy++;
    configUI.add(label, c);
    c.gridx = 1;
    configUI.add(singleComboBox, c);
    singleComboBox.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                updateRenderer();
            }
        }
    });

    c.gridx = 2;
    JButton config = new JButton(UI.getImageIcon("gear"));
    configUI.add(config, c);
    config.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (singleRenderer == null) {
                return;
            }
            //                JOptionPane.showmess
            int returnVal = JOptionPane.showConfirmDialog(CoolMapMaster.getCMainFrame(),
                    singleRenderer.getConfigUI(), "Default Renderer Config", JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.PLAIN_MESSAGE, null);
            if (returnVal == JOptionPane.OK_OPTION) {
                updateRenderer();
            }
        }
    });

    c.gridx = 1;
    c.gridy++;
    c.gridwidth = 1;
    configUI.add(singleLegend, c);

    //////////////////////////////////////////////////////////////
    c.gridx = 0;
    c.gridy++;
    c.gridwidth = 1;
    label = new JLabel("Row Group:");
    label.setToolTipText("Renderer for row ontology nodes");
    configUI.add(label, c);
    c.gridx = 1;
    configUI.add(rowComboBox, c);
    c.gridx++;
    config = new JButton(UI.getImageIcon("gear"));
    configUI.add(config, c);
    config.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (rowGroupRenderer == null) {
                return;
            }
            //                JOptionPane.showmess
            int returnVal = JOptionPane.showConfirmDialog(CoolMapMaster.getCMainFrame(),
                    rowGroupRenderer.getConfigUI(), "Row Group Renderer Config", JOptionPane.OK_CANCEL_OPTION,
                    JOptionPane.PLAIN_MESSAGE, null);
            if (returnVal == JOptionPane.OK_OPTION) {
                updateRenderer();
            }

        }
    });
    rowComboBox.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                updateRenderer();
            }
        }
    });

    c.gridx = 1;
    c.gridy++;
    c.gridwidth = 1;
    configUI.add(rowLegend, c);

    c.gridx = 0;
    c.gridy++;
    c.gridwidth = 1;
    label = new JLabel("Column Group:");
    label.setToolTipText("Renderer for column ontology nodes");
    configUI.add(label, c);
    c.gridx = 1;
    configUI.add(columnComboBox, c);
    c.gridx++;
    config = new JButton(UI.getImageIcon("gear"));
    configUI.add(config, c);
    config.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (columnGroupRenderer == null) {
                return;
            }
            //                JOptionPane.showmess
            int returnVal = JOptionPane.showConfirmDialog(CoolMapMaster.getCMainFrame(),
                    columnGroupRenderer.getConfigUI(), "Column Group Renderer Config",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null);
            if (returnVal == JOptionPane.OK_OPTION) {
                updateRenderer();
            }
        }
    });

    c.gridx = 1;
    c.gridy++;
    c.gridwidth = 1;
    configUI.add(columnLegend, c);
    columnComboBox.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                updateRenderer();
            }
        }
    });

    c.gridx = 0;
    c.gridy++;
    c.gridwidth = 1;
    label = new JLabel("Row & Column Group:");
    label.setToolTipText("Renderer for row and column ontology nodes");
    configUI.add(label, c);
    c.gridx = 1;
    configUI.add(rowColumnComboBox, c);
    c.gridx++;
    config = new JButton(UI.getImageIcon("gear"));
    configUI.add(config, c);
    config.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (rowColumnGroupRenderer == null) {
                return;
            }
            //                JOptionPane.showmess
            int returnVal = JOptionPane.showConfirmDialog(CoolMapMaster.getCMainFrame(),
                    rowColumnGroupRenderer.getConfigUI(), "Row + Column Group Renderer Config",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null);
            if (returnVal == JOptionPane.OK_OPTION) {
                updateRenderer();
            }
        }
    });
    rowColumnComboBox.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                updateRenderer();
            }
        }
    });

    c.gridx = 1;
    c.gridy++;
    c.gridwidth = 1;
    configUI.add(rowColumnLegend, c);

    JButton button = new JButton("Apply Changes", UI.getImageIcon("refresh"));
    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            updateRenderer();
        }
    });

    c.gridx = 0;
    c.gridy++;
    c.gridwidth = 2;
    configUI.add(button, c);

    singleComboBox.setRenderer(new ComboRenderer());
    rowComboBox.setRenderer(new ComboRenderer());
    columnComboBox.setRenderer(new ComboRenderer());
    rowColumnComboBox.setRenderer(new ComboRenderer());

    _updateLists();

}

From source file:com.projity.dialog.AbstractDialog.java

/**
 *
 *///from   w  w  w  . j a va 2s  .  c o  m
public void onOk() {
    if (!bind(false))
        return;
    setDialogResult(JOptionPane.OK_OPTION);
    setVisible(false);
    // desactivateListeners();
}

From source file:net.sf.jabref.gui.preftabs.PreferencesDialog.java

public PreferencesDialog(JabRefFrame parent) {
    super(parent, Localization.lang("JabRef preferences"), false);
    JabRefPreferences prefs = JabRefPreferences.getInstance();
    frame = parent;//w  w w. j  a  v  a  2 s.  c  om

    main = new JPanel();
    JPanel mainPanel = new JPanel();
    JPanel lower = new JPanel();

    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(mainPanel, BorderLayout.CENTER);
    getContentPane().add(lower, BorderLayout.SOUTH);

    final CardLayout cardLayout = new CardLayout();
    main.setLayout(cardLayout);

    List<PrefsTab> tabs = new ArrayList<>();
    tabs.add(new GeneralTab(prefs));
    tabs.add(new NetworkTab(prefs));
    tabs.add(new FileTab(frame, prefs));
    tabs.add(new FileSortTab(prefs));
    tabs.add(new EntryEditorPrefsTab(frame, prefs));
    tabs.add(new GroupsPrefsTab(prefs));
    tabs.add(new AppearancePrefsTab(prefs));
    tabs.add(new ExternalTab(frame, this, prefs));
    tabs.add(new TablePrefsTab(prefs));
    tabs.add(new TableColumnsTab(prefs, parent));
    tabs.add(new LabelPatternPrefTab(prefs, parent.getCurrentBasePanel()));
    tabs.add(new PreviewPrefsTab(prefs));
    tabs.add(new NameFormatterTab(prefs));
    tabs.add(new ImportSettingsTab(prefs));
    tabs.add(new XmpPrefsTab(prefs));
    tabs.add(new AdvancedTab(prefs));

    // add all tabs
    tabs.forEach(tab -> main.add((Component) tab, tab.getTabName()));

    mainPanel.setBorder(BorderFactory.createEtchedBorder());

    String[] tabNames = tabs.stream().map(PrefsTab::getTabName).toArray(String[]::new);
    JList<String> chooser = new JList<>(tabNames);
    chooser.setBorder(BorderFactory.createEtchedBorder());
    // Set a prototype value to control the width of the list:
    chooser.setPrototypeCellValue("This should be wide enough");
    chooser.setSelectedIndex(0);
    chooser.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    // Add the selection listener that will show the correct panel when
    // selection changes:
    chooser.addListSelectionListener(e -> {
        if (e.getValueIsAdjusting()) {
            return;
        }
        String o = chooser.getSelectedValue();
        cardLayout.show(main, o);
    });

    JPanel buttons = new JPanel();
    buttons.setLayout(new GridLayout(4, 1));
    buttons.add(importPreferences, 0);
    buttons.add(exportPreferences, 1);
    buttons.add(showPreferences, 2);
    buttons.add(resetPreferences, 3);

    JPanel westPanel = new JPanel();
    westPanel.setLayout(new BorderLayout());
    westPanel.add(chooser, BorderLayout.CENTER);
    westPanel.add(buttons, BorderLayout.SOUTH);
    mainPanel.setLayout(new BorderLayout());
    mainPanel.add(main, BorderLayout.CENTER);
    mainPanel.add(westPanel, BorderLayout.WEST);

    JButton ok = new JButton(Localization.lang("OK"));
    JButton cancel = new JButton(Localization.lang("Cancel"));
    ok.addActionListener(new OkAction());
    CancelAction cancelAction = new CancelAction();
    cancel.addActionListener(cancelAction);
    lower.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
    ButtonBarBuilder buttonBarBuilder = new ButtonBarBuilder(lower);
    buttonBarBuilder.addGlue();
    buttonBarBuilder.addButton(ok);
    buttonBarBuilder.addButton(cancel);
    buttonBarBuilder.addGlue();

    // Key bindings:
    KeyBinder.bindCloseDialogKeyToCancelAction(this.getRootPane(), cancelAction);

    // Import and export actions:
    exportPreferences.setToolTipText(Localization.lang("Export preferences to file"));
    exportPreferences.addActionListener(e -> {
        String filename = FileDialogs.getNewFile(frame, new File(System.getProperty("user.home")),
                Collections.singletonList(".xml"), JFileChooser.SAVE_DIALOG, false);
        if (filename == null) {
            return;
        }
        File file = new File(filename);
        if (!file.exists() || (JOptionPane.showConfirmDialog(PreferencesDialog.this,
                Localization.lang("'%0' exists. Overwrite file?", file.getName()),
                Localization.lang("Export preferences"),
                JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION)) {

            try {
                prefs.exportPreferences(filename);
            } catch (JabRefException ex) {
                LOGGER.warn(ex.getMessage(), ex);
                JOptionPane.showMessageDialog(PreferencesDialog.this, ex.getLocalizedMessage(),
                        Localization.lang("Export preferences"), JOptionPane.ERROR_MESSAGE);
            }
        }
    });

    importPreferences.setToolTipText(Localization.lang("Import preferences from file"));
    importPreferences.addActionListener(e -> {
        String filename = FileDialogs.getNewFile(frame, new File(System.getProperty("user.home")),
                Collections.singletonList(".xml"), JFileChooser.OPEN_DIALOG, false);
        if (filename != null) {
            try {
                prefs.importPreferences(filename);
                updateAfterPreferenceChanges();
                JOptionPane.showMessageDialog(PreferencesDialog.this,
                        Localization.lang("You must restart JabRef for this to come into effect."),
                        Localization.lang("Import preferences"), JOptionPane.WARNING_MESSAGE);
            } catch (JabRefException ex) {
                LOGGER.warn(ex.getMessage(), ex);
                JOptionPane.showMessageDialog(PreferencesDialog.this, ex.getLocalizedMessage(),
                        Localization.lang("Import preferences"), JOptionPane.ERROR_MESSAGE);
            }
        }
    });

    showPreferences.addActionListener(
            e -> new PreferencesFilterDialog(new JabRefPreferencesFilter(Globals.prefs), frame)
                    .setVisible(true));
    resetPreferences.addActionListener(e -> {
        if (JOptionPane.showConfirmDialog(PreferencesDialog.this,
                Localization.lang("Are you sure you want to reset all settings to default values?"),
                Localization.lang("Reset preferences"),
                JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
            try {
                prefs.clear();
                JOptionPane.showMessageDialog(PreferencesDialog.this,
                        Localization.lang("You must restart JabRef for this to come into effect."),
                        Localization.lang("Reset preferences"), JOptionPane.WARNING_MESSAGE);
            } catch (BackingStoreException ex) {
                LOGGER.warn(ex.getMessage(), ex);
                JOptionPane.showMessageDialog(PreferencesDialog.this, ex.getLocalizedMessage(),
                        Localization.lang("Reset preferences"), JOptionPane.ERROR_MESSAGE);
            }
            updateAfterPreferenceChanges();
        }
    });

    setValues();

    pack();

}

From source file:captureplugin.drivers.DeviceCreatorDialog.java

/**
 * OK was pressed//from w ww . j a va  2s.c o m
 */
private void okPressed() {

    if (StringUtils.isBlank(mName.getText())) {
        JOptionPane.showMessageDialog(this, mLocalizer.msg("NoName", "No Name was entered"),
                Localizer.getLocalization(Localizer.I18N_ERROR), JOptionPane.ERROR_MESSAGE);

    } else {
        mRetmode = JOptionPane.OK_OPTION;
        setVisible(false);
    }
}

From source file:com.massabot.codesender.utils.FirmwareUtils.java

public synchronized static void initialize() {
    System.out.println("Initializing firmware... ...");
    File firmwareConfig = new File(SettingsFactory.getSettingsDirectory(), FIRMWARE_CONFIG_DIRNAME);

    // Create directory if it's missing.
    if (!firmwareConfig.exists()) {
        firmwareConfig.mkdirs();/*from  w ww .  ja  va2s .  co  m*/
    }

    FileSystem fileSystem = null;

    // Copy firmware config files.
    try {
        final String dir = "/resources/firmware_config/";

        URI location = FirmwareUtils.class.getResource(dir).toURI();

        Path myPath;
        if (location.getScheme().equals("jar")) {
            try {
                // In case the filesystem already exists.
                fileSystem = FileSystems.getFileSystem(location);
            } catch (FileSystemNotFoundException e) {
                // Otherwise create the new filesystem.
                fileSystem = FileSystems.newFileSystem(location, Collections.<String, String>emptyMap());
            }

            myPath = fileSystem.getPath(dir);
        } else {
            myPath = Paths.get(location);
        }

        Stream<Path> files = Files.walk(myPath, 1);
        for (Path path : (Iterable<Path>) () -> files.iterator()) {
            System.out.println(path);
            final String name = path.getFileName().toString();
            File fwConfig = new File(firmwareConfig, name);
            if (name.endsWith(".json")) {
                boolean copyFile = !fwConfig.exists();
                ControllerSettings jarSetting = getSettingsForStream(Files.newInputStream(path));

                // If the file is outdated... ask the user (once).
                if (fwConfig.exists()) {
                    ControllerSettings current = getSettingsForStream(new FileInputStream(fwConfig));
                    boolean outOfDate = current.getVersion() < jarSetting.getVersion();
                    if (outOfDate && !userNotified && !overwriteOldFiles) {
                        int result = NarrowOptionPane.showNarrowConfirmDialog(200,
                                Localization.getString("settings.file.outOfDate.message"),
                                Localization.getString("settings.file.outOfDate.title"),
                                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        overwriteOldFiles = result == JOptionPane.OK_OPTION;
                        userNotified = true;
                    }

                    if (overwriteOldFiles) {
                        copyFile = true;
                        jarSetting.getProcessorConfigs().Custom = current.getProcessorConfigs().Custom;
                    }
                }

                // Copy file from jar to firmware_config directory.
                if (copyFile) {
                    try {
                        save(fwConfig, jarSetting);
                    } catch (IOException ex) {
                        logger.log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    } catch (Exception ex) {
        String errorMessage = String.format("%s %s", Localization.getString("settings.file.generalError"),
                ex.getLocalizedMessage());
        GUIHelpers.displayErrorDialog(errorMessage);
        logger.log(Level.SEVERE, errorMessage, ex);
    } finally {
        if (fileSystem != null) {
            try {
                fileSystem.close();
            } catch (IOException ex) {
                logger.log(Level.SEVERE, "Problem closing filesystem.", ex);
            }
        }
    }

    configFiles.clear();
    for (File f : firmwareConfig.listFiles()) {
        try {
            ControllerSettings config = new Gson().fromJson(new FileReader(f), ControllerSettings.class);
            // ConfigLoader config = new ConfigLoader(f);
            configFiles.put(config.getName(), new ConfigTuple(config, f));
        } catch (FileNotFoundException | JsonSyntaxException | JsonIOException ex) {
            GUIHelpers.displayErrorDialog("Unable to load configuration files: " + f.getAbsolutePath());
        }
    }
}