Java Code Examples for javax.swing.JOptionPane#YES_OPTION

The following examples show how to use javax.swing.JOptionPane#YES_OPTION . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JPanelConfiguration.java    From nordpos with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean deactivate() {
    
    boolean haschanged = false;
    for (PanelConfig c: m_panelconfig) {
        if (c.hasChanged()) {
            haschanged = true;
        }
    }        
    
    
    if (haschanged) {
        int res = JOptionPane.showConfirmDialog(this, AppLocal.getIntString("message.wannasave"), AppLocal.getIntString("title.editor"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (res == JOptionPane.YES_OPTION) {
            saveProperties();
            return true;
        } else {
            return res == JOptionPane.NO_OPTION;
        }
    } else {
        return true;
    }
}
 
Example 2
Source File: Tools.java    From Zettelkasten with GNU General Public License v3.0 6 votes vote down vote up
/**
 *
 * @param linktype
 * @param data
 * @param displayedZettel
 * @return
 */
public static boolean removeHyperlink(String linktype, Daten data, int displayedZettel) {
    // here we have a cross reference to another entry
    if (linktype.startsWith("#cr_")) {
        // only remove manual links from activated entry!
        if (displayedZettel != data.getCurrentZettelPos()) {
            return false;
        }
        try {
            // if we have just a single selection, use phrasing for that message
            String msg = resourceMap.getString("askForDeleteManLinksMsgSingle");
            // ask whether author really should be deleted
            int option = JOptionPane.showConfirmDialog(null, msg, resourceMap.getString("askForDeleteManLinksTitle"), JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
            // if yes, do so
            if (JOptionPane.YES_OPTION == option) {
                // remove manual link
                data.deleteManualLinks(new String[]{linktype.substring(4)});
                return true;
            }
        } catch (IndexOutOfBoundsException e) {
            Constants.zknlogger.log(Level.WARNING, e.getLocalizedMessage());
        }
    }
    return false;
}
 
Example 3
Source File: SamplesRunner.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void editCSSFile(Sample sample) {
    try {
        if (!sample.isCSSProject(ctx)) {
            int res = JOptionPane.showConfirmDialog(view, "This sample doesn't currently use CSS. Activate CSS now?", "Activate CSS?", JOptionPane.YES_NO_OPTION);
            if (res == JOptionPane.YES_OPTION) {
                sample.activateCSS(ctx);
            } else {
                return;
            }
        }
        if (Desktop.isDesktopSupported()) {
            Desktop.getDesktop().edit(sample.getThemeCSSFile(ctx));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 4
Source File: EditorControl.java    From settlers-remake with MIT License 6 votes vote down vote up
/**
 * Check if saved, if not ask user
 * 
 * @return true to continue, false to cancel
 */
private boolean checkSaved() {
	if (!undoRedo.isChangedSinceLastSave()) {
		return true;
	} else {
		int result = JOptionPane.showConfirmDialog(window, EditorLabels.getLabel("ctrl.save-chages"), "JSettler",
				JOptionPane.YES_NO_CANCEL_OPTION);
		if (result == JOptionPane.YES_OPTION) {
			save();
			return true;
		} else if (result == JOptionPane.NO_OPTION) {
			return true;
		}
		// cancel
		return false;
	}
}
 
Example 5
Source File: UploadHistory.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
private void clearHistoryButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearHistoryButtonActionPerformed
    ThemeCheck.apply(null);
    if (JOptionPane.showConfirmDialog(this, Translation.T().
            confirmClear(), "", JOptionPane.YES_NO_OPTION)
            != JOptionPane.YES_OPTION) {
        return;
    }

    NULogger.getLogger().info("Clearing the upload history");
    try {
        //delete the file
        new File(System.getProperty("user.home") + File.separator + "recent.log").delete();
    } catch (Exception e) {
        NULogger.getLogger().warning(e.toString());
        System.err.println(e);
    }

    //What a cool way to clear rows?
    model.setRowCount(0);
}
 
Example 6
Source File: AbstractDemoFrame.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Exits the application, but only if the user agrees.
 *
 * @return false if the user decides not to exit the application.
 */
protected boolean attemptExit()
{
  final boolean close =
      JOptionPane.showConfirmDialog(this,
          getResources().getString("exitdialog.message"),
          getResources().getString("exitdialog.title"),
          JOptionPane.YES_NO_OPTION,
          JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION;
  if (close)
  {
    if (ignoreEmbeddedConfig ||
        "false".equals(ClassicEngineBoot.getInstance().getGlobalConfig().getConfigProperty
            (EMBEDDED_KEY, "false")))
    {
      System.exit(0);
    }
    else
    {
      setVisible(false);
      dispose();
    }
  }

  return close;
}
 
Example 7
Source File: SignUI.java    From Websocket-Smart-Card-Signer with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void showFileSave(List<Data> dataSignedList) throws Exception{
    for(Data dataSigned : dataSignedList){
        JFileChooser jfc = new JFileChooser();
        jfc.setMultiSelectionEnabled(false);
        jfc.setSelectedFile(new File(dataSigned.id+(dataSigned.id.toLowerCase().endsWith(".pdf") || dataSigned.id.toLowerCase().endsWith(".p7m")?"":(dataSigned.config.saveAsPDF?".pdf":".p7m"))));
        jfc.setDialogTitle("Save file");
        SignUtils.playBeeps(1);
        if(jfc.showSaveDialog(null) != JFileChooser.APPROVE_OPTION)
            continue;
        String fileName = jfc.getSelectedFile().getAbsolutePath();
        if(new File(fileName).exists()){
            SignUtils.playBeeps(1);
            if(JOptionPane.showConfirmDialog(null, "Overwrite the file " + fileName + " ?", "WARNING", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION)
                continue;
        }
        
        IOUtils.writeFile(dataSigned.data, fileName, false);
    }
}
 
Example 8
Source File: DrawingFrame.java    From osp with GNU General Public License v3.0 5 votes vote down vote up
public void saveXML() {
  JFileChooser chooser = OSPRuntime.getChooser();
  int result = chooser.showSaveDialog(null);
  if(result==JFileChooser.APPROVE_OPTION) {
    OSPRuntime.chooserDir = chooser.getCurrentDirectory().toString();
    File file = chooser.getSelectedFile();
    // check to see if file already exists
    if(file.exists()) {
      int selected = JOptionPane.showConfirmDialog(null, DisplayRes.getString("DrawingFrame.ReplaceExisting_message")+file.getName() //$NON-NLS-1$
        +DisplayRes.getString("DrawingFrame.QuestionMark"),                           //$NON-NLS-1$
          DisplayRes.getString("DrawingFrame.ReplaceFile_option_title"),              //$NON-NLS-1$
            JOptionPane.YES_NO_CANCEL_OPTION);
      if(selected!=JOptionPane.YES_OPTION) {
        return;
      }
    }
    String fileName = XML.getRelativePath(file.getAbsolutePath());
    if((fileName==null)||fileName.trim().equals("")) {                                //$NON-NLS-1$
      return;
    }
    int i = fileName.toLowerCase().lastIndexOf(".xml");                               //$NON-NLS-1$
    if(i!=fileName.length()-4) {
      fileName += ".xml";                                                             //$NON-NLS-1$
    }
    try {
      // if drawingPanel provides an xml loader, save the drawingPanel
      Method method = drawingPanel.getClass().getMethod("getLoader", (Class[]) null); //$NON-NLS-1$
      if((method!=null)&&Modifier.isStatic(method.getModifiers())) {
        XMLControl xml = new XMLControlElement(drawingPanel);
        xml.write(fileName);
      }
    } catch(NoSuchMethodException ex) {
      // this drawingPanel cannot be saved
      return;
    }
  }
}
 
Example 9
Source File: FrmMain.java    From yeti with MIT License 5 votes vote down vote up
private void miDeleteAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miDeleteAllActionPerformed
    if (JOptionPane.showConfirmDialog(null, "Are you sure you want to delete this job?", "Confirmation",
            JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
        currentWorkflowController.removeJob(tblJobs.getSelectedRow());
    }
    setJobDetail(currentNetworkLayout);
}
 
Example 10
Source File: CampaignHistoryInfoPane.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e)
{
	if (fieldsNotBlank())
	{
		int ret = JOptionPane.showConfirmDialog(this,
			"<html>This chronicle has been written in." + "<br>Are you sure you want to delete it?</html>",
			Constants.APPLICATION_NAME, JOptionPane.YES_NO_OPTION);
		if (ret != JOptionPane.YES_OPTION)
		{//The user has not agreed so exit out
			return;
		}
	}
	handler.deleteChroniclePane(this, entry);
}
 
Example 11
Source File: KeyConfigure.java    From tn5250j with GNU General Public License v2.0 5 votes vote down vote up
private boolean isAvailable(KeyEvent ke) {

      boolean exists = true;

      if (isLinux) {
          exists = KeyMapper.isKeyStrokeDefined(ke,isAltGr);
      }
      else {
         exists = KeyMapper.isKeyStrokeDefined(ke);
      }

      if (exists) {

         Object[] args = {getKeyDescription(ke)};

         int result = JOptionPane.showConfirmDialog(this,
                     LangTool.messageFormat("messages.mapKeyWarning",args),
                     LangTool.getString("key.labelKeyExists"),
                     JOptionPane.YES_NO_OPTION,
                     JOptionPane.WARNING_MESSAGE);

         if (result == JOptionPane.YES_OPTION)
            return true;
         else
            return false;
      }
      return !exists;
   }
 
Example 12
Source File: ElistView.java    From ramus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
    if (JOptionPane.showConfirmDialog(null, GlobalResourcesManager
                    .getString("DeleteActiveElementsDialog.Warning"),
            GlobalResourcesManager.getString("ConfirmMessage.Title"),
            JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION)
        return;
    component.deleteElements();
}
 
Example 13
Source File: DSWorkbenchFarmManager.java    From dsworkbench with Apache License 2.0 5 votes vote down vote up
/**
 * Delete all selected farms
 */
private void deleteSelection() {
    int rows[] = jFarmTable.getSelectedRows();
    if (rows == null || rows.length == 0) {
        showInfo("Keine Farm gewählt");
        return;
    }

    if (JOptionPaneHelper.showQuestionConfirmBox(this,
            rows.length + " Farm(en) und alle Informationen wirklich löschen?", "Löschen", "Nein",
            "Ja") != JOptionPane.YES_OPTION) {
        return;
    }

    FarmManager.getSingleton().invalidate();
    List<FarmInformation> toDelete = new LinkedList<>();
    for (int row : rows) {
        toDelete.add((FarmInformation) FarmManager.getSingleton().getAllElements()
                .get(jFarmTable.convertRowIndexToModel(row)));
    }

    for (FarmInformation delete : toDelete) {
        FarmManager.getSingleton().removeFarm(delete.getVillage());
    }

    FarmManager.getSingleton().revalidate(true);
    showInfo(rows.length + " Farm(en) gelöscht");
}
 
Example 14
Source File: FavoritesDialog.java    From nextreports-designer with Apache License 2.0 5 votes vote down vote up
protected boolean ok() {

        List<FavoriteEntry> list = favPanel.getSelectedFavorites();

        if (list.size() == 0) {
            Show.info(I18NSupport.getString("favorites.remove.select"));
            return false;
        }

        Object[] options = {I18NSupport.getString("optionpanel.yes"), I18NSupport.getString("optionpanel.no")};
        int option = JOptionPane.showOptionDialog(this,
                I18NSupport.getString("favorites.remove.confirm"),
                I18NSupport.getString("report.util.confirm"),
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null, options, options[1]);

        if (option == JOptionPane.YES_OPTION) {
            List<FavoriteEntry> favorites = FavoritesUtil.loadFavorites();
            favorites.removeAll(list);
            FavoritesUtil.saveFavorites(favorites);
        } else {
            return false;
        }

        return true;
    }
 
Example 15
Source File: ConstructionWizard.java    From mars-sim with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("restriction")
public synchronized void confirmSiteLocation(ConstructionSite site, ConstructionManager constructionManager,
		boolean isAtPreDefinedLocation, ConstructionStageInfo stageInfo, int constructionSkill) {
	//System.out.println("ConstructionWizard : entering confirmSiteLocation()");

       // Determine location and facing for the new building.
	double xLoc = site.getXLocation();
	double yLoc = site.getYLocation();
	double scale = mapPanel.getScale();

	Settlement currentS = settlementWindow.getMapPanel().getSettlement();
	if (currentS != constructionManager.getSettlement()) {

		if (mainScene != null) {
			mainScene.setSettlement(constructionManager.getSettlement());
		}
		else {
   			//desktop.openToolWindow(SettlementWindow.NAME);
			settlementWindow.getMapPanel().getSettlementTransparentPanel().getSettlementListBox()
				.setSelectedItem(constructionManager.getSettlement());
		}
	}
 		// set up the Settlement Map Tool to display the suggested location of the building
	mapPanel.reCenter();
	mapPanel.moveCenter(xLoc*scale, yLoc*scale);
	//mapPanel.setShowConstructionLabels(true);
	//mapPanel.getSettlementTransparentPanel().getConstructionLabelMenuItem().setSelected(true);

	String header = null;
	String title = null;
	String message = "(1) Will default to \"Yes\" in 90 secs unless timer is cancelled."
   			+ " (2) To manually place a site, click on \"Use Mouse\" button.";
	StringProperty msg = new SimpleStringProperty(message);
	String name = null;

	if (stageInfo != null) {
		name = stageInfo.getName();
		title = "A New " + Conversion.capitalize(stageInfo.getName()).replace(" X ", " x ") + " at " + constructionManager.getSettlement();
        // stageInfo.getType() is less descriptive than stageInfo.getName()
	}
	else {
		name = site.getName();
		title = "A New " + Conversion.capitalize(site.getName()).replace(" X ", " x ") + " at " + constructionManager.getSettlement();
	}

	if (isAtPreDefinedLocation) {
		header = "Would you like to place the " +  name + " at its default position? ";
	}
	else {
		header = "Would you like to place the " + name + " at this position? ";
	}


       if (mainScene != null) {
       	alertDialog(title, header, msg, constructionManager, site, true, stageInfo, constructionSkill);

	} else {

        desktop.openAnnouncementWindow("Pause for Construction Wizard");
        AnnouncementWindow aw = desktop.getAnnouncementWindow();
        Point location = MouseInfo.getPointerInfo().getLocation();
        double Xloc = location.getX() - aw.getWidth() * 2;
		double Yloc = location.getY() - aw.getHeight() * 2;
		aw.setLocation((int)Xloc, (int)Yloc);

		int reply = JOptionPane.showConfirmDialog(aw, header, TITLE, JOptionPane.YES_NO_OPTION);
		//repaint();

		if (reply == JOptionPane.YES_OPTION) {
            logger.info("The construction site is set");
		}
		else {
			//constructionManager.removeConstructionSite(site);
			//site = new ConstructionSite();
			site = positionNewSite(site);//, constructionSkill);
			confirmSiteLocation(site, constructionManager, false, stageInfo, constructionSkill);
		}

		desktop.disposeAnnouncementWindow();
	}

}
 
Example 16
Source File: FileData.java    From sldeditor with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Checks if input/output files are valid.
 *
 * @param runFromCommandLine the run from command line
 * @param errorMessages the error messages
 * @return true, if is valid
 */
public boolean isValid(boolean runFromCommandLine, List<String> errorMessages) {
    boolean inputValid = false;
    boolean outputValid = false;

    if(inputFile != null)
    {
        if(!inputFile.isFile())
        {
            errorMessages.add("Input file is not a file.");
        }
        else
        {
            if(!inputFile.exists())
            {
                errorMessages.add("Input file does not exist.");
            }
            else
            {
                inputValid = true;
            }
        }
    }
    else
    {
        errorMessages.add("Input file not specified.");
    }

    if(outputFile != null)
    {
        if(runFromCommandLine)
        {
            if(outputFile.exists() && !overwrite)
            {
                errorMessages.add("Output file already exists, use -overwrite option on the command line.");
            }
            else
            {
                outputValid = true;
            }
        }
        else
        {
            if(outputFile.exists() && !overwrite)
            {
                int result = JOptionPane.showConfirmDialog(null, "Overwrite output file?", "Output file exists",
                        JOptionPane.YES_NO_OPTION);
                if(result == JOptionPane.YES_OPTION)
                {
                    overwrite = true;
                    outputValid = true;
                }
                else
                {
                    errorMessages.add("Output file already exists.");
                }
            }
            else
            {
                outputValid = true;
            }
        }

        // Check folder containing file exists
        if(outputValid)
        {
            if(outputFile.getParentFile() != null)
            {
                outputValid = outputFile.getParentFile().exists();
                if(!outputValid)
                {
                    errorMessages.add("Path of output file does not exist.");
                }
            }
        }
    }
    else
    {
        errorMessages.add("Output file not specified.");
    }

    return inputValid && outputValid;
}
 
Example 17
Source File: AnalysisView.java    From iBioSim with Apache License 2.0 4 votes vote down vote up
private void addAbstractionMethod(ActionEvent e)
{
  JPanel addAbsPanel = new JPanel(new BorderLayout());
  JComboBox<String> absList = new JComboBox<String>();
  if (e.getSource() == addPreAbs)
  {
    absList.addItem("complex-formation-and-sequestering-abstraction");
  }
  absList.addItem("operator-site-reduction-abstraction");
  absList.addItem("absolute-activation/inhibition-generator");
  absList.addItem("absolute-inhibition-generator");
  absList.addItem("birth-death-generator");
  absList.addItem("birth-death-generator2");
  absList.addItem("birth-death-generator3");
  absList.addItem("birth-death-generator4");
  absList.addItem("birth-death-generator5");
  absList.addItem("birth-death-generator6");
  absList.addItem("birth-death-generator7");
  absList.addItem("degradation-stoichiometry-amplifier");
  absList.addItem("degradation-stoichiometry-amplifier2");
  absList.addItem("degradation-stoichiometry-amplifier3");
  absList.addItem("degradation-stoichiometry-amplifier4");
  absList.addItem("degradation-stoichiometry-amplifier5");
  absList.addItem("degradation-stoichiometry-amplifier6");
  absList.addItem("degradation-stoichiometry-amplifier7");
  absList.addItem("degradation-stoichiometry-amplifier8");
  absList.addItem("dimer-to-monomer-substitutor");
  absList.addItem("dimerization-reduction");
  absList.addItem("dimerization-reduction-level-assignment");
  absList.addItem("distribute-transformer");
  absList.addItem("enzyme-kinetic-qssa-1");
  absList.addItem("enzyme-kinetic-rapid-equilibrium-1");
  absList.addItem("enzyme-kinetic-rapid-equilibrium-2");
  absList.addItem("final-state-generator");
  absList.addItem("inducer-structure-transformer");
  absList.addItem("irrelevant-species-remover");
  absList.addItem("kinetic-law-constants-simplifier");
  absList.addItem("max-concentration-reaction-adder");
  absList.addItem("modifier-constant-propagation");
  absList.addItem("modifier-structure-transformer");
  absList.addItem("multiple-products-reaction-eliminator");
  absList.addItem("multiple-reactants-reaction-eliminator");
  absList.addItem("nary-order-unary-transformer");
  absList.addItem("nary-order-unary-transformer2");
  absList.addItem("nary-order-unary-transformer3");
  absList.addItem("operator-site-forward-binding-remover");
  absList.addItem("operator-site-forward-binding-remover2");
  absList.addItem("pow-kinetic-law-transformer");
  absList.addItem("ppta");
  absList.addItem("reversible-reaction-structure-transformer");
  absList.addItem("reversible-to-irreversible-transformer");
  absList.addItem("similar-reaction-combiner");
  absList.addItem("single-reactant-product-reaction-eliminator");
  absList.addItem("stoichiometry-amplifier");
  absList.addItem("stoichiometry-amplifier2");
  absList.addItem("stoichiometry-amplifier3");
  absList.addItem("stop-flag-generator");
  addAbsPanel.add(absList, "Center");
  String[] options = { "Add", "Cancel" };
  int value = JOptionPane.showOptionDialog(Gui.frame, addAbsPanel, "Add abstraction method", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
  if (value == JOptionPane.YES_OPTION)
  {
    if (e.getSource() == addPreAbs)
    {
      Utility.add(preAbs, absList.getSelectedItem());
    }
    else if (e.getSource() == addLoopAbs)
    {
      Utility.add(loopAbs, absList.getSelectedItem());
    }
    else
    {
      Utility.add(postAbs, absList.getSelectedItem());
    }
  }
}
 
Example 18
Source File: ExportToImagesDialog.java    From ramus with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected void onOk() {
    final File dir = new File(directory.getText());
    if (dir.exists()) {
        if (!dir.isDirectory()) {
            JOptionPane.showMessageDialog(this, MessageFormat.format(
                    ResourceLoader.getString("FileIsNotADirectory"),
                    directory.getText()));
        } else {
            for (File file : dir.listFiles()) {
                if (file.isFile()) {
                    if (JOptionPane.showConfirmDialog(this, ResourceLoader
                                    .getString("DirectoryIsNotEmpty"), UIManager
                                    .getString("OptionPane.titleText"),
                            JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION)
                        return;
                    break;
                }
            }
        }
    } else {
        if (!dir.mkdirs()) {
            JOptionPane.showMessageDialog(this, ResourceLoader
                    .getString("CanNotCreateADirectory"));
        }
    }

    final BusyDialog dialog = new BusyDialog(this, ResourceLoader.getString("ExportingBusy"));

    Thread export = new Thread("Export-to-images") {
        @Override
        public void run() {
            int i = 0;
            int[] js = chackedPanel.getSelected();
            for (Function f : chackedPanel.getSelectedFunctions()) {
                try {
                    String prefix = Integer.toString(js[i] + 1);
                    while (prefix.length() < 2)
                        prefix = "0" + prefix;
                    exportToFile(dir, f, prefix + "_");
                    i++;
                } catch (IOException e) {
                    SwingUtilities.invokeLater(new Runnable() {

                        @Override
                        public void run() {
                            dialog.setVisible(false);
                        }
                    });
                    JOptionPane.showMessageDialog(
                            ExportToImagesDialog.this, e
                                    .getLocalizedMessage());
                    if (Metadata.DEBUG)
                        e.printStackTrace();
                    return;
                }
            }
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    dialog.setVisible(false);
                }
            });
            Options.setString(LAST_IMG_EXPORT_DIRECTORY, directory
                    .getText());
            ExportToImagesDialog.super.onOk();
        }
    };
    export.start();
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            if (ExportToImagesDialog.this.isVisible())
                dialog.setVisible(true);
        }
    });
}
 
Example 19
Source File: DeckEditorScreen.java    From magarena with GNU General Public License v3.0 4 votes vote down vote up
private void saveDeck() {

        final MagicDeck deck = contentPanel.getDeck();

        if (deck.isEmpty()) {
            ScreenController.showWarningMessage(MText.get(_S15));
            return;
        }

        // Prompt for name of deck (which is also used as the filename).
        final String deckName = (String) JOptionPane.showInputDialog(
            ScreenController.getFrame(),
            MText.get(_S31),
            MText.get(_S32),
            JOptionPane.QUESTION_MESSAGE,
            null, null, deck.getName()
        );
        if (deckName == null || deckName.trim().isEmpty()) {
            return;
        }

        // add '.dec' file extension to end of filename if not present.
        String filename = deckName.trim();
        if (!filename.endsWith(DeckUtils.DECK_EXTENSION)) {
            filename += DeckUtils.DECK_EXTENSION;
        }

        // create deck file path - returns null if not valid (eg invalid char in filename).
        Path deckFilePath = tryGetDeckFilePath(filename);
        if (deckFilePath == null) {
            return;
        }

        // if deck file already exists ask for overwrite confirmation.
        if (Files.exists(deckFilePath)) {
            int response = JOptionPane.showConfirmDialog(
                ScreenController.getFrame(),
                MText.get(_S17),
                MText.get(_S18),
                JOptionPane.YES_NO_OPTION
            );
            if (response != JOptionPane.YES_OPTION) {
                return;
            }
        }

        // finally can try to save deck to file.
        if (DeckUtils.saveDeck(deckFilePath.toString(), deck)) {
            setDeck(DeckUtils.loadDeckFromFile(deckFilePath));
            setMostRecentDeck(deckFilePath.toString());
        } else {
            ScreenController.showWarningMessage(MText.get(_S20));
        }

    }
 
Example 20
Source File: RenameKeyPairAction.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Rename the currently selected entry
 */
public void renameSelectedEntry() {
	try {
		KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
		KeyStoreState currentState = history.getCurrentState();

		String alias = kseFrame.getSelectedEntryAlias();

		Password password = getEntryPassword(alias, currentState);

		if (password == null) {
			return;
		}

		KeyStoreState newState = currentState.createBasisForNextState(this);

		KeyStore keyStore = newState.getKeyStore();

		Key privateKey = keyStore.getKey(alias, password.toCharArray());

		Certificate[] certs = keyStore.getCertificateChain(alias);
		certs = X509CertUtil.orderX509CertChain(X509CertUtil.convertCertificates(certs));

		DGetAlias dGetAlias = new DGetAlias(frame, res.getString("RenameKeyPairAction.NewEntryAlias.Title"), alias);
		dGetAlias.setLocationRelativeTo(frame);
		dGetAlias.setVisible(true);
		String newAlias = dGetAlias.getAlias();

		if (newAlias == null) {
			return;
		}

		if (newAlias.equalsIgnoreCase(alias)) {
			JOptionPane.showMessageDialog(frame,
					MessageFormat.format(res.getString("RenameKeyPairAction.RenameAliasIdentical.message"), alias),
					res.getString("RenameKeyPairAction.RenameEntry.Title"), JOptionPane.WARNING_MESSAGE);
			return;
		}

		if (keyStore.containsAlias(newAlias)) {
			String message = MessageFormat.format(res.getString("RenameKeyPairAction.OverWriteEntry.message"),
					newAlias);

			int selected = JOptionPane.showConfirmDialog(frame, message,
					res.getString("RenameKeyPairAction.RenameEntry.Title"), JOptionPane.YES_NO_OPTION);
			if (selected != JOptionPane.YES_OPTION) {
				return;
			}

			keyStore.deleteEntry(newAlias);
			newState.removeEntryPassword(newAlias);
		}

		keyStore.setKeyEntry(newAlias, privateKey, password.toCharArray(), certs);
		newState.setEntryPassword(newAlias, new Password(password));

		keyStore.deleteEntry(alias);
		newState.removeEntryPassword(alias);

		currentState.append(newState);

		kseFrame.updateControls(true);
	} catch (Exception ex) {
		DError.displayError(frame, ex);
	}
}