Example usage for javax.swing JOptionPane YES_NO_CANCEL_OPTION

List of usage examples for javax.swing JOptionPane YES_NO_CANCEL_OPTION

Introduction

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

Prototype

int YES_NO_CANCEL_OPTION

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

Click Source Link

Document

Type used for showConfirmDialog.

Usage

From source file:burlov.ultracipher.swing.SwingGuiApplication.java

public boolean canExit() {
    if (hasChanges) {
        /*//from   ww w  . ja v a  2 s  .co m
         * Wenn es ungespeicherte Aenderungen gibt, dann Benutzer fragen
        */
        int ret = JOptionPane.showConfirmDialog(getMainFrame(), "Save changes before exit?", "",
                JOptionPane.YES_NO_CANCEL_OPTION);
        switch (ret) {
        case JOptionPane.CANCEL_OPTION:
            return false;
        case JOptionPane.NO_OPTION:
            return true;
        case JOptionPane.YES_OPTION:
            /*
            * Speichern anstossen
            */
            saveDatabase();
            /*
             * Nur wenn Speichern erfolgreich war 'true' zurueckgeben
             */
            return !hasChanges;
        default:
            return false;
        }
    } else {
        return true;
    }
}

From source file:com.pdk.DisassembleElfAction.java

private void showList() {
    Project project = NetbeansUtil.getPeterProject();
    File dir = new File(project.getProjectDirectory().getPath());
    Collection<File> files = FileUtils.listFiles(dir, new String[] { "o", "exe" }, true);
    if (files.isEmpty()) {
        return;/*  ww w. j  a  v  a  2  s  .com*/
    }
    files.add(new File(dir.getAbsolutePath() + File.separator + "kernel/kernel"));
    Iterator<File> iter = files.iterator();
    while (iter.hasNext()) {
        File file = iter.next();
        String relativePath = file.getAbsolutePath().substring(dir.getAbsolutePath().length());
        if (relativePath.startsWith("/toolchain/")) {
            iter.remove();
        }
    }
    String[] arr = new String[files.size()];
    iter = files.iterator();
    int x = 0;
    while (iter.hasNext()) {
        File file = iter.next();
        String relativePath = file.getAbsolutePath().substring(dir.getAbsolutePath().length() + 1);
        arr[x] = relativePath;
        x++;
    }
    Arrays.sort(arr, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            if (o1.startsWith("kernel/")) {
                return -1;
            } else if (o1.startsWith("kernel/")) {
                return 1;
            } else {
                return o1.compareTo(o2);
            }
        }
    });

    String file = (String) JOptionPane.showInputDialog(null, null, "Please select an elf file",
            JOptionPane.QUESTION_MESSAGE, null, arr, arr[0]);
    if (file != null) {
        try {
            Object[] options = { "Disasm", "Sections", "Cancel" };
            int n = JOptionPane.showOptionDialog(null, "Please select", "Question",
                    JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]);

            if (n == 2) {
                return;
            }
            String command2 = null;
            if (n == 0) {
                command2 = "i586-peter-elf-objdump -S";
            } else if (n == 1) {
                command2 = "i586-peter-elf-readelf -S";
            }
            if (command2 == null) {
                return;
            }
            final String command = "/toolchain/bin/" + command2 + " " + file;

            process = Runtime.getRuntime().exec(command, null, dir);
            InputStreamReader isr = new InputStreamReader(process.getInputStream());
            final BufferedReader br = new BufferedReader(isr, 1024 * 1024 * 50);
            final JProgressBarDialog d = new JProgressBarDialog(new JFrame(),
                    "i586-peter-elf-objdump -S " + file, true);

            d.progressBar.setIndeterminate(true);
            d.progressBar.setStringPainted(true);
            d.progressBar.setString("Updating");
            d.addCancelEventListener(this);
            Thread longRunningThread = new Thread() {
                public void run() {
                    try {
                        lines = new StringBuilder();
                        String line;
                        stop = false;
                        while (!stop && (line = br.readLine()) != null) {
                            d.progressBar.setString(line);
                            lines.append(line).append("\n");
                        }
                        DisassembleDialog disassembleDialog = new DisassembleDialog();
                        disassembleDialog.setTitle(command);
                        if (((DefaultComboBoxModel) disassembleDialog.enhancedTextArea1.fontComboBox.getModel())
                                .getIndexOf("Monospaced") != -1) {
                            disassembleDialog.enhancedTextArea1.fontComboBox.setSelectedItem("Monospaced");
                        }
                        if (((DefaultComboBoxModel) disassembleDialog.enhancedTextArea1.fontComboBox.getModel())
                                .getIndexOf("Monospaced.plain") != -1) {
                            disassembleDialog.enhancedTextArea1.fontComboBox
                                    .setSelectedItem("Monospaced.plain");
                        }
                        disassembleDialog.enhancedTextArea1.fontComboBox.setSelectedItem("Monospaced");
                        disassembleDialog.enhancedTextArea1.setText(lines.toString());
                        disassembleDialog.setVisible(true);
                    } catch (Exception ex) {
                        ModuleLib.log(CommonLib.printException(ex));
                    }
                }
            };
            d.thread = longRunningThread;
            d.setVisible(true);
        } catch (Exception ex) {
            ModuleLib.log(CommonLib.printException(ex));
        }
    }
}

From source file:com.ebixio.virtmus.stats.StatsLogger.java

/**
 * Ask the user if they want to help by uploading stats logs.
 *//*from   w  w w .jav  a2s  .c  o  m*/
private UploadStats promptUser() {
    String yes = NbBundle.getMessage(StatsLogger.class, "BTN_Yes"),
            maybeLater = NbBundle.getMessage(StatsLogger.class, "BTN_MaybeLater"),
            never = NbBundle.getMessage(StatsLogger.class, "BTN_Never");

    Icon icon = ImageUtilities.loadImageIcon("com/ebixio/virtmus/resources/VirtMus32x32.png", false);
    int userChoice = JOptionPane.showOptionDialog(null, NbBundle.getMessage(StatsLogger.class, "MSG_Text"),
            NbBundle.getMessage(StatsLogger.class, "MSG_Title"), JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE, icon, new Object[] { yes, maybeLater, never }, yes);

    switch (userChoice) {
    case 0:
        return UploadStats.Yes;
    case 2:
        return UploadStats.No;
    case 1:
        return UploadStats.Maybe;
    case -1: // User closed the dialog. Leave it as "Unknown".
    default:
        return UploadStats.Unknown;
    }
}

From source file:DialogDemo.java

/** Creates the panel shown by the first tab. */
private JPanel createSimpleDialogBox() {
    final int numButtons = 4;
    JRadioButton[] radioButtons = new JRadioButton[numButtons];
    final ButtonGroup group = new ButtonGroup();

    JButton showItButton = null;/* www .jav a  2  s . co m*/

    final String defaultMessageCommand = "default";
    final String yesNoCommand = "yesno";
    final String yeahNahCommand = "yeahnah";
    final String yncCommand = "ync";

    radioButtons[0] = new JRadioButton("OK (in the L&F's words)");
    radioButtons[0].setActionCommand(defaultMessageCommand);

    radioButtons[1] = new JRadioButton("Yes/No (in the L&F's words)");
    radioButtons[1].setActionCommand(yesNoCommand);

    radioButtons[2] = new JRadioButton("Yes/No " + "(in the programmer's words)");
    radioButtons[2].setActionCommand(yeahNahCommand);

    radioButtons[3] = new JRadioButton("Yes/No/Cancel " + "(in the programmer's words)");
    radioButtons[3].setActionCommand(yncCommand);

    for (int i = 0; i < numButtons; i++) {
        group.add(radioButtons[i]);
    }
    radioButtons[0].setSelected(true);

    showItButton = new JButton("Show it!");
    showItButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String command = group.getSelection().getActionCommand();

            // ok dialog
            if (command == defaultMessageCommand) {
                JOptionPane.showMessageDialog(frame, "Eggs aren't supposed to be green.");

                // yes/no dialog
            } else if (command == yesNoCommand) {
                int n = JOptionPane.showConfirmDialog(frame, "Would you like green eggs and ham?",
                        "An Inane Question", JOptionPane.YES_NO_OPTION);
                if (n == JOptionPane.YES_OPTION) {
                    setLabel("Ewww!");
                } else if (n == JOptionPane.NO_OPTION) {
                    setLabel("Me neither!");
                } else {
                    setLabel("Come on -- tell me!");
                }

                // yes/no (not in those words)
            } else if (command == yeahNahCommand) {
                Object[] options = { "Yes, please", "No way!" };
                int n = JOptionPane.showOptionDialog(frame, "Would you like green eggs and ham?",
                        "A Silly Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
                        options, options[0]);
                if (n == JOptionPane.YES_OPTION) {
                    setLabel("You're kidding!");
                } else if (n == JOptionPane.NO_OPTION) {
                    setLabel("I don't like them, either.");
                } else {
                    setLabel("Come on -- 'fess up!");
                }

                // yes/no/cancel (not in those words)
            } else if (command == yncCommand) {
                Object[] options = { "Yes, please", "No, thanks", "No eggs, no ham!" };
                int n = JOptionPane.showOptionDialog(frame,
                        "Would you like some green eggs to go " + "with that ham?", "A Silly Question",
                        JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
                        options[2]);
                if (n == JOptionPane.YES_OPTION) {
                    setLabel("Here you go: green eggs and ham!");
                } else if (n == JOptionPane.NO_OPTION) {
                    setLabel("OK, just the ham, then.");
                } else if (n == JOptionPane.CANCEL_OPTION) {
                    setLabel("Well, I'm certainly not going to eat them!");
                } else {
                    setLabel("Please tell me what you want!");
                }
            }
            return;
        }
    });

    return createPane(simpleDialogDesc + ":", radioButtons, showItButton);
}

From source file:com.igormaznitsa.zxpspritecorrector.files.TAPPlugin.java

@Override
public void writeTo(final File file, final ZXPolyData data, final SessionData session) throws IOException {
    final int saveAsSeparateFiles = JOptionPane.showConfirmDialog(this.mainFrame,
            "Save each block as a separated file?", "Separate files", JOptionPane.YES_NO_CANCEL_OPTION);
    if (saveAsSeparateFiles == JOptionPane.CANCEL_OPTION)
        return;/*from w  ww  .ja  va 2 s. c  o m*/

    final String baseName = file.getName();
    final String baseZXName = FilenameUtils.getBaseName(baseName);
    if (saveAsSeparateFiles == JOptionPane.YES_OPTION) {

        final FileNameDialog fileNameDialog = new FileNameDialog(this.mainFrame, "Saving as separated files",
                new String[] { addNumberToFileName(baseName, 0), addNumberToFileName(baseName, 1),
                        addNumberToFileName(baseName, 2), addNumberToFileName(baseName, 3) },
                new String[] { prepareNameForTAP(baseZXName, 0), prepareNameForTAP(baseZXName, 1),
                        prepareNameForTAP(baseZXName, 2), prepareNameForTAP(baseZXName, 3) },
                null);
        fileNameDialog.setVisible(true);
        if (fileNameDialog.approved()) {
            final String[] fileNames = fileNameDialog.getFileName();
            final String[] zxNames = fileNameDialog.getZxName();
            for (int i = 0; i < 4; i++) {
                final byte[] headerblock = makeHeaderBlock(zxNames[i], data.getInfo().getStartAddress(),
                        data.length());
                final byte[] datablock = makeDataBlock(data.getDataForCPU(i));
                final byte[] dataToSave = JBBPOut.BeginBin().Byte(wellTapBlock(headerblock))
                        .Byte(wellTapBlock(datablock)).End().toByteArray();

                final File fileToSave = new File(file.getParent(), fileNames[i]);
                if (!saveDataToFile(fileToSave, dataToSave))
                    return;
            }
        }
    } else {
        final FileNameDialog fileNameDialog = new FileNameDialog(this.mainFrame, "Save as " + baseName, null,
                new String[] { prepareNameForTAP(baseZXName, 0), prepareNameForTAP(baseZXName, 1),
                        prepareNameForTAP(baseZXName, 2), prepareNameForTAP(baseZXName, 3) },
                null);
        fileNameDialog.setVisible(true);
        if (fileNameDialog.approved()) {
            final String[] zxNames = fileNameDialog.getZxName();
            final JBBPOut out = JBBPOut.BeginBin();
            for (int i = 0; i < 4; i++) {
                final byte[] headerblock = makeHeaderBlock(zxNames[i], data.getInfo().getStartAddress(),
                        data.length());
                final byte[] datablock = makeDataBlock(data.getDataForCPU(i));
                out.Byte(wellTapBlock(headerblock)).Byte(wellTapBlock(datablock));
            }
            saveDataToFile(file, out.End().toByteArray());
        }
    }

}

From source file:de.ipk_gatersleben.ag_nw.graffiti.plugins.gui.webstart.MainM.java

private static int askForEnablingKEGG() {
    JOptionPane.showMessageDialog(null, "<html><h3>KEGG License Status Evaluation</h3>"
            + "While VANTED is available as a academic research tool at no cost to commercial and non-commercial users, for using<br>"
            + "KEGG related functions, it is necessary for all users to adhere to the KEGG license.<br>"
            + "For using VANTED you need also be aware of information about licenses and conditions for<br>"
            + "usage, listed at the program info dialog and the VANTED website (http://vanted.ipk-gatersleben.de).<br><br>"
            + "VANTED does not distribute information from KEGG but contains functionality for the online-access to <br>"
            + "information from KEGG website.<br><br>"
            + "<b>Before these functions are available to you, you should  carefully read the following license information<br>"
            + "and decide if it is legit for you to use the KEGG related program functions. If you choose not to use the KEGG functions<br>"
            + "all other features of this application are still available and fully working.",
            "VANTED Program Features Initialization", JOptionPane.INFORMATION_MESSAGE);

    JOptionPane.showMessageDialog(null,
            "<html><h3>KEGG License Status Evaluation</h3>" + MenuItemInfoDialog.getKEGGlibText(),
            "VANTED Program Features Initialization", JOptionPane.INFORMATION_MESSAGE);

    int result = JOptionPane.showConfirmDialog(null, "<html><h3>Enable KEGG functions?",
            "VANTED Program Features Initialization", JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE);
    return result;
}

From source file:be.fedict.eid.tsl.tool.TslTool.java

@Override
public void actionPerformed(ActionEvent event) {
    String command = event.getActionCommand();
    if (EXIT_ACTION_COMMAND.equals(command)) {
        System.exit(0);//from ww w  .jav a  2 s.  c o  m
    } else if (OPEN_ACTION_COMMAND.equals(command)) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Open TSL");
        int returnValue = fileChooser.showOpenDialog(this);
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            displayTsl(fileChooser.getSelectedFile());
        }
    } else if (ABOUT_ACTION_COMMAND.equals(command)) {
        JOptionPane.showMessageDialog(this,
                "eID TSL Tool\n" + "Copyright (C) 2009-2013 FedICT\n" + "http://code.google.com/p/eid-tsl/",
                "About", JOptionPane.INFORMATION_MESSAGE);
    } else if (CLOSE_ACTION_COMMAND.equals(command)) {
        if (this.activeTslInternalFrame.getTrustServiceList().hasChanged()) {
            int result = JOptionPane.showConfirmDialog(this, "TSL has been changed.\n" + "Save the TSL?",
                    "Save", JOptionPane.YES_NO_CANCEL_OPTION);
            if (JOptionPane.CANCEL_OPTION == result) {
                return;
            }
            if (JOptionPane.YES_OPTION == result) {
                try {
                    this.activeTslInternalFrame.save();
                } catch (IOException e) {
                    LOG.error("IO error: " + e.getMessage(), e);
                }
            }
        }
        try {
            this.activeTslInternalFrame.setClosed(true);
        } catch (PropertyVetoException e) {
            LOG.warn("property veto error: " + e.getMessage(), e);
        }
    } else if (SIGN_ACTION_COMMAND.equals(command)) {
        LOG.debug("sign");
        TrustServiceList trustServiceList = this.activeTslInternalFrame.getTrustServiceList();
        if (trustServiceList.hasSignature()) {
            int confirmResult = JOptionPane.showConfirmDialog(this,
                    "TSL is already signed.\n" + "Resign the TSL?", "Resign", JOptionPane.OK_CANCEL_OPTION);
            if (JOptionPane.CANCEL_OPTION == confirmResult) {
                return;
            }
        }
        SignSelectPkcs11FinishablePanel pkcs11Panel = new SignSelectPkcs11FinishablePanel();
        WizardDescriptor wizardDescriptor = new WizardDescriptor(
                new WizardDescriptor.Panel[] { new SignInitFinishablePanel(), pkcs11Panel,
                        new SignSelectCertificatePanel(pkcs11Panel, trustServiceList),
                        new SignFinishFinishablePanel() });
        wizardDescriptor.setTitle("Sign TSL");
        wizardDescriptor.putProperty("WizardPanel_autoWizardStyle", Boolean.TRUE);
        DialogDisplayer dialogDisplayer = DialogDisplayer.getDefault();
        Dialog wizardDialog = dialogDisplayer.createDialog(wizardDescriptor);
        wizardDialog.setVisible(true);
    } else if (SAVE_ACTION_COMMAND.equals(command)) {
        LOG.debug("save");
        try {
            this.activeTslInternalFrame.save();
            this.saveMenuItem.setEnabled(false);
        } catch (IOException e) {
            LOG.debug("IO error: " + e.getMessage(), e);
        }
    } else if (SAVE_AS_ACTION_COMMAND.equals(command)) {
        LOG.debug("save as");
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Save As");
        int result = fileChooser.showSaveDialog(this);
        if (JFileChooser.APPROVE_OPTION == result) {
            File tslFile = fileChooser.getSelectedFile();
            if (tslFile.exists()) {
                int confirmResult = JOptionPane.showConfirmDialog(this,
                        "File already exists.\n" + tslFile.getAbsolutePath() + "\n" + "Overwrite file?",
                        "Overwrite", JOptionPane.OK_CANCEL_OPTION);
                if (JOptionPane.CANCEL_OPTION == confirmResult) {
                    return;
                }
            }
            try {
                this.activeTslInternalFrame.saveAs(tslFile);
            } catch (IOException e) {
                LOG.debug("IO error: " + e.getMessage(), e);
            }
            this.saveMenuItem.setEnabled(false);
        }
    } else if (EXPORT_ACTION_COMMAND.equals(command)) {
        LOG.debug("export");
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Export to PDF");
        int result = fileChooser.showSaveDialog(this);
        if (JFileChooser.APPROVE_OPTION == result) {
            File pdfFile = fileChooser.getSelectedFile();
            if (pdfFile.exists()) {
                int confirmResult = JOptionPane.showConfirmDialog(this,
                        "File already exists.\n" + pdfFile.getAbsolutePath() + "\n" + "Overwrite file?",
                        "Overwrite", JOptionPane.OK_CANCEL_OPTION);
                if (JOptionPane.CANCEL_OPTION == confirmResult) {
                    return;
                }
            }
            try {
                this.activeTslInternalFrame.export(pdfFile);
            } catch (IOException e) {
                LOG.debug("IO error: " + e.getMessage(), e);
            }
        }
    } else if ("TSL-BE-2010-T1".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2010, Trimester.FIRST);
        displayTsl("*TSL-BE-2010-T1.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2010-T2".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2010, Trimester.SECOND);
        displayTsl("*TSL-BE-2010-T2.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2010-T3".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2010, Trimester.THIRD);
        displayTsl("*TSL-BE-2010-T3.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2011-T1".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2011, Trimester.FIRST);
        displayTsl("*TSL-BE-2011-T1.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2011-T2".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2011, Trimester.SECOND);
        displayTsl("*TSL-BE-2011-T2.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2011-T3".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2011, Trimester.THIRD);
        displayTsl("*TSL-BE-2011-T3.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2012-T1".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2012, Trimester.FIRST);
        displayTsl("*TSL-BE-2012-T1.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2012-T2".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2012, Trimester.SECOND);
        displayTsl("*TSL-BE-2012-T2.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2012-T3".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2012, Trimester.THIRD);
        displayTsl("*TSL-BE-2012-T3.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2013-T1".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2013, Trimester.FIRST);
        displayTsl("*TSL-BE-2013-T1.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2013-T2".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2013, Trimester.SECOND);
        displayTsl("*TSL-BE-2013-T2.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2013-T3".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2013, Trimester.THIRD);
        displayTsl("*TSL-BE-2013-T3.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2014-T1".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2014, Trimester.FIRST);
        displayTsl("*TSL-BE-2014-T1.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2014-T2".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2014, Trimester.SECOND);
        displayTsl("*TSL-BE-2014-T2.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2014-T3".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2014, Trimester.THIRD);
        displayTsl("*TSL-BE-2014-T3.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2015-T1".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2015, Trimester.FIRST);
        displayTsl("*TSL-BE-2015-T1.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2015-T2".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2015, Trimester.SECOND);
        displayTsl("*TSL-BE-2015-T2.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    } else if ("TSL-BE-2015-T3".equals(command)) {
        TrustServiceList trustServiceList = BelgianTrustServiceListFactory.newInstance(2015, Trimester.THIRD);
        displayTsl("*TSL-BE-2015-T3.xml", trustServiceList);
        this.saveMenuItem.setEnabled(false);
    }
}

From source file:net.sf.jabref.exporter.SaveDatabaseAction.java

private boolean saveDatabase(File file, boolean selectedOnly, Charset encoding) throws SaveException {
    SaveSession session;/*  w  w w  .jav a 2 s  .  co m*/
    frame.block();
    try {
        SavePreferences prefs = SavePreferences.loadForSaveFromPreferences(Globals.prefs)
                .withEncoding(encoding);
        BibDatabaseWriter databaseWriter = new BibDatabaseWriter();
        if (selectedOnly) {
            session = databaseWriter.savePartOfDatabase(panel.getBibDatabaseContext(), prefs,
                    panel.getSelectedEntries());

        } else {
            session = databaseWriter.saveDatabase(panel.getBibDatabaseContext(), prefs);

        }
        panel.registerUndoableChanges(session);

    } catch (UnsupportedCharsetException ex2) {
        JOptionPane.showMessageDialog(frame,
                Localization.lang("Could not save file.") + Localization
                        .lang("Character encoding '%0' is not supported.", encoding.displayName()),
                Localization.lang("Save database"), JOptionPane.ERROR_MESSAGE);
        throw new SaveException("rt");
    } catch (SaveException ex) {
        if (ex == SaveException.FILE_LOCKED) {
            throw ex;
        }
        if (ex.specificEntry()) {
            // Error occured during processing of
            // be. Highlight it:
            int row = panel.mainTable.findEntry(ex.getEntry());
            int topShow = Math.max(0, row - 3);
            panel.mainTable.setRowSelectionInterval(row, row);
            panel.mainTable.scrollTo(topShow);
            panel.showEntry(ex.getEntry());
        } else {
            LOGGER.error("Problem saving file", ex);
        }

        JOptionPane.showMessageDialog(frame,
                Localization.lang("Could not save file.") + ".\n" + ex.getMessage(),
                Localization.lang("Save database"), JOptionPane.ERROR_MESSAGE);
        throw new SaveException("rt");

    } finally {
        frame.unblock();
    }

    boolean commit = true;
    if (!session.getWriter().couldEncodeAll()) {
        FormBuilder builder = FormBuilder.create()
                .layout(new FormLayout("left:pref, 4dlu, fill:pref", "pref, 4dlu, pref"));
        JTextArea ta = new JTextArea(session.getWriter().getProblemCharacters());
        ta.setEditable(false);
        builder.add(Localization.lang("The chosen encoding '%0' could not encode the following characters:",
                session.getEncoding().displayName())).xy(1, 1);
        builder.add(ta).xy(3, 1);
        builder.add(Localization.lang("What do you want to do?")).xy(1, 3);
        String tryDiff = Localization.lang("Try different encoding");
        int answer = JOptionPane.showOptionDialog(frame, builder.getPanel(), Localization.lang("Save database"),
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null,
                new String[] { Localization.lang("Save"), tryDiff, Localization.lang("Cancel") }, tryDiff);

        if (answer == JOptionPane.NO_OPTION) {
            // The user wants to use another encoding.
            Object choice = JOptionPane.showInputDialog(frame, Localization.lang("Select encoding"),
                    Localization.lang("Save database"), JOptionPane.QUESTION_MESSAGE, null,
                    Encodings.ENCODINGS_DISPLAYNAMES, encoding);
            if (choice == null) {
                commit = false;
            } else {
                Charset newEncoding = Charset.forName((String) choice);
                return saveDatabase(file, selectedOnly, newEncoding);
            }
        } else if (answer == JOptionPane.CANCEL_OPTION) {
            commit = false;
        }

    }

    try {
        if (commit) {
            session.commit(file);
            panel.setEncoding(encoding); // Make sure to remember which encoding we used.
        } else {
            session.cancel();
        }
    } catch (SaveException e) {
        int ans = JOptionPane.showConfirmDialog(null,
                Localization.lang("Save failed during backup creation") + ". "
                        + Localization.lang("Save without backup?"),
                Localization.lang("Unable to create backup"), JOptionPane.YES_NO_OPTION);
        if (ans == JOptionPane.YES_OPTION) {
            session.setUseBackup(false);
            session.commit(file);
            panel.setEncoding(encoding);
        } else {
            commit = false;
        }
    }

    return commit;
}

From source file:imageviewer.system.ImageViewerClient.java

private void initialize(CommandLine args) {

    // First, process all the different command line arguments that we
    // need to override and/or send onwards for initialization.

    boolean fullScreen = (args.hasOption("fullscreen")) ? true : false;
    String dir = (args.hasOption("dir")) ? args.getOptionValue("dir") : null;
    String type = (args.hasOption("type")) ? args.getOptionValue("type") : "DICOM";
    String prefix = (args.hasOption("client")) ? args.getOptionValue("client") : null;

    LOG.info("Java home environment: " + System.getProperty("java.home"));

    // Logging system taken care of through properties file.  Check
    // for JAI.  Set up JAI accordingly with the size of the cache
    // tile and to recycle cached tiles as needed.

    verifyJAI();// w ww.  j a v  a  2  s  .c o  m
    TileCache tc = JAI.getDefaultInstance().getTileCache();
    tc.setMemoryCapacity(32 * 1024 * 1024);
    TileScheduler ts = JAI.createTileScheduler();
    ts.setPriority(Thread.MAX_PRIORITY);
    JAI.getDefaultInstance().setTileScheduler(ts);
    JAI.getDefaultInstance().setRenderingHint(JAI.KEY_CACHED_TILE_RECYCLING_ENABLED, Boolean.TRUE);

    // Set up the frame and everything else.  First, try and set the
    // UI manager to use our look and feel because it's groovy and
    // lets us control the GUI components much better.

    try {
        UIManager.setLookAndFeel(new ImageViewerLookAndFeel());
        LookAndFeelAddons.setAddon(ImageViewerLookAndFeelAddons.class);
    } catch (Exception exc) {
        LOG.error("Could not set imageViewer L&F.");
    }

    // Load up the ApplicationContext information...

    ApplicationContext ac = ApplicationContext.getContext();
    if (ac == null) {
        LOG.error("Could not load configuration, exiting.");
        System.exit(1);
    }

    // Override the client node information based on command line
    // arguments...Make sure that the files are there, otherwise just
    // default to a local configuration.

    String hostname = new String("localhost");
    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (Exception exc) {
    }

    String[] gatewayConfigs = (prefix != null)
            ? (new String[] { "resources/server/" + prefix + "GatewayConfig.xml",
                    (String) ac.getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG),
                    "resources/server/" + hostname + "GatewayConfig.xml",
                    "resources/server/localGatewayConfig.xml" })
            : (new String[] { (String) ac.getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG),
                    "resources/server/" + hostname + "GatewayConfig.xml",
                    "resources/server/localGatewayConfig.xml" });
    String[] nodeConfigs = (prefix != null)
            ? (new String[] { "resources/server/" + prefix + "NodeConfig.xml",
                    (String) ac.getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE),
                    "resources/server/" + hostname + "NodeConfig.xml", "resources/server/localNodeConfig.xml" })
            : (new String[] { (String) ac.getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE),
                    "resources/server/" + hostname + "NodeConfig.xml",
                    "resources/server/localNodeConfig.xml" });

    for (int loop = 0; loop < gatewayConfigs.length; loop++) {
        String s = gatewayConfigs[loop];
        if ((s != null) && (s.length() != 0) && (!"null".equals(s))) {
            File f = new File(s);
            if (f.exists()) {
                ac.setProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG, s);
                break;
            }
        }
    }

    LOG.info("Using gateway config: " + ac.getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG));

    for (int loop = 0; loop < nodeConfigs.length; loop++) {
        String s = nodeConfigs[loop];
        if ((s != null) && (s.length() != 0) && (!"null".equals(s))) {
            File f = new File(s);
            if (f.exists()) {
                ac.setProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE, s);
                break;
            }
        }
    }
    LOG.info("Using client config: " + ac.getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE));

    // Load the layouts and set the default window/level manager...

    LayoutFactory.initialize();
    DefaultWindowLevelManager dwlm = new DefaultWindowLevelManager();

    // Create the main JFrame, set its behavior, and let the
    // ApplicationPanel know the glassPane and layeredPane.  Set the
    // menubar based on reading in the configuration menus.

    mainFrame = new JFrame("imageviewer");
    try {
        ArrayList<Image> iconList = new ArrayList<Image>();
        iconList.add(ImageIO.read(new File("resources/icons/mii.png")));
        iconList.add(ImageIO.read(new File("resources/icons/mii32.png")));
        mainFrame.setIconImages(iconList);
    } catch (Exception exc) {
    }

    mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    mainFrame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            int confirm = ApplicationPanel.getInstance().showDialog(
                    "Are you sure you want to quit imageViewer?", null, JOptionPane.QUESTION_MESSAGE,
                    JOptionPane.OK_CANCEL_OPTION, UIManager.getIcon("Dialog.shutdownIcon"));
            if (confirm == JOptionPane.OK_OPTION) {
                boolean hasUnsaved = SaveStack.getInstance().hasUnsavedItems();
                if (hasUnsaved) {
                    int saveResult = ApplicationPanel.getInstance().showDialog(
                            "There is still unsaved data.  Do you want to save this data in the local archive?",
                            null, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION);
                    if (saveResult == JOptionPane.CANCEL_OPTION)
                        return;
                    if (saveResult == JOptionPane.YES_OPTION)
                        SaveStack.getInstance().saveAll();
                }
                LOG.info("Shutting down imageServer local archive...");
                try {
                    ImageViewerClientNode.getInstance().shutdown();
                } catch (Exception exc) {
                    LOG.error("Problem shutting down imageServer local archive...");
                } finally {
                    System.exit(0);
                }
            }
        }
    });

    String menuFile = (String) ApplicationContext.getContext().getProperty(ac.CONFIG_MENUS);
    String ribbonFile = (String) ApplicationContext.getContext().getProperty(ac.CONFIG_RIBBON);
    if (menuFile != null) {
        JMenuBar mb = new JMenuBar();
        mb.setBackground(Color.black);
        MenuReader.parseFile(menuFile, mb);
        mainFrame.setJMenuBar(mb);
        ApplicationContext.getContext().setApplicationMenuBar(mb);
    } else if (ribbonFile != null) {
        RibbonReader rr = new RibbonReader();
        JRibbon jr = rr.parseFile(ribbonFile);
        mainFrame.getContentPane().add(jr, BorderLayout.NORTH);
        ApplicationContext.getContext().setApplicationRibbon(jr);
    }
    mainFrame.getContentPane().add(ApplicationPanel.getInstance(), BorderLayout.CENTER);
    ApplicationPanel.getInstance().setGlassPane((JPanel) (mainFrame.getGlassPane()));
    ApplicationPanel.getInstance().setLayeredPane(mainFrame.getLayeredPane());

    // Load specified plugins...has to occur after the menus are
    // created, btw.

    PluginLoader.initialize("config/plugins.xml");

    // Detect operating system...

    String osName = System.getProperty("os.name");
    ApplicationContext.getContext().setProperty(ApplicationContext.OS_NAME, osName);
    LOG.info("Detected operating system: " + osName);

    // Try and hack the searched library paths if it's windows so we
    // can add a local dll path...

    try {
        if (osName.contains("Windows")) {
            Field f = ClassLoader.class.getDeclaredField("usr_paths");
            f.setAccessible(true);
            String[] paths = (String[]) f.get(null);
            String[] tmp = new String[paths.length + 1];
            System.arraycopy(paths, 0, tmp, 0, paths.length);
            File currentPath = new File(".");
            tmp[paths.length] = currentPath.getCanonicalPath() + "/lib/dll/";
            f.set(null, tmp);
            f.setAccessible(false);
        }
    } catch (Exception exc) {
        LOG.error("Error attempting to dynamically set library paths.");
    }

    // Get screen resolution...

    GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice()
            .getDefaultConfiguration();
    Rectangle r = gc.getBounds();
    LOG.info("Detected screen resolution: " + (int) r.getWidth() + "x" + (int) r.getHeight());

    // Try and see if Java3D is installed, and if so, what version...

    try {
        VirtualUniverse vu = new VirtualUniverse();
        Map m = vu.getProperties();
        String s = (String) m.get("j3d.version");
        LOG.info("Detected Java3D version: " + s);
    } catch (Throwable t) {
        LOG.info("Unable to detect Java3D installation");
    }

    // Try and see if native JOGL is installed...

    try {
        System.loadLibrary("jogl");
        ac.setProperty(ApplicationContext.JOGL_DETECTED, Boolean.TRUE);
        LOG.info("Detected native libraries for JOGL");
    } catch (Throwable t) {
        LOG.info("Unable to detect native JOGL installation");
        ac.setProperty(ApplicationContext.JOGL_DETECTED, Boolean.FALSE);
    }

    // Start the local client node to connect to the network and the
    // local archive running on this machine...Thread the connection
    // process so it doesn't block the imageViewerClient creating this
    // instance.  We may not be connected to the given gateway, so the
    // socketServer may go blah...

    final boolean useNetwork = (args.hasOption("nonet")) ? false : true;
    ApplicationPanel.getInstance().addStatusMessage("ImageViewer is starting up, please wait...");
    if (useNetwork)
        LOG.info("Starting imageServer client to join network - please wait...");
    Thread t = new Thread(new Runnable() {
        public void run() {
            try {
                ImageViewerClientNode.getInstance(
                        (String) ApplicationContext.getContext()
                                .getProperty(ApplicationContext.IMAGESERVER_GATEWAY_CONFIG),
                        (String) ApplicationContext.getContext()
                                .getProperty(ApplicationContext.IMAGESERVER_CLIENT_NODE),
                        useNetwork);
                ApplicationPanel.getInstance().addStatusMessage("Ready");
            } catch (Exception exc) {
                exc.printStackTrace();
            }
        }
    });
    t.setPriority(9);
    t.start();

    this.fullScreen = fullScreen;
    mainFrame.setUndecorated(fullScreen);

    // Set the view to encompass the default screen.

    if (fullScreen) {
        Insets i = Toolkit.getDefaultToolkit().getScreenInsets(gc);
        mainFrame.setLocation(r.x + i.left, r.y + i.top);
        mainFrame.setSize(r.width - i.left - i.right, r.height - i.top - i.bottom);
    } else {
        mainFrame.setSize(1100, 800);
        mainFrame.setLocation(r.x + 200, r.y + 100);
    }

    if (dir != null)
        ApplicationPanel.getInstance().load(dir, type);

    timer = new Timer();
    timer.schedule(new GarbageCollectionTimer(), 5000, 2500);
    mainFrame.setVisible(true);
}

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

private boolean tryXmpImport(String fileName, ExternalFileType fileType, NamedCompound edits) {

    if (!"pdf".equals(fileType.getExtension())) {
        return false;
    }/*from   w  w  w. j  a  v a  2  s . com*/

    List<BibEntry> xmpEntriesInFile;
    try {
        xmpEntriesInFile = XMPUtil.readXMP(fileName, Globals.prefs);
    } catch (IOException e) {
        LOGGER.warn("Problem reading XMP", e);
        return false;
    }

    if ((xmpEntriesInFile == null) || xmpEntriesInFile.isEmpty()) {
        return false;
    }

    JLabel confirmationMessage = new JLabel(Localization.lang("The PDF contains one or several BibTeX-records.")
            + "\n"
            + Localization.lang("Do you want to import these as new entries into the current database?"));

    int reply = JOptionPane.showConfirmDialog(frame, confirmationMessage,
            Localization.lang("XMP-metadata found in PDF: %0", fileName), JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE);

    if (reply == JOptionPane.CANCEL_OPTION) {
        return true; // The user canceled thus that we are done.
    }
    if (reply == JOptionPane.NO_OPTION) {
        return false;
    }

    // reply == JOptionPane.YES_OPTION)

    /*
     * TODO Extract Import functionality from ImportMenuItem then we could
     * do:
     *
     * ImportMenuItem importer = new ImportMenuItem(frame, (mainTable ==
     * null), new PdfXmpImporter());
     *
     * importer.automatedImport(new String[] { fileName });
     */

    boolean isSingle = xmpEntriesInFile.size() == 1;
    BibEntry single = isSingle ? xmpEntriesInFile.get(0) : null;

    boolean success = true;

    String destFilename;

    if (linkInPlace.isSelected()) {
        destFilename = FileUtil
                .shortenFileName(new File(fileName), panel.getBibDatabaseContext().getFileDirectory())
                .toString();
    } else {
        if (renameCheckBox.isSelected()) {
            destFilename = fileName;
        } else {
            destFilename = single.getCiteKey() + "." + fileType.getExtension();
        }

        if (copyRadioButton.isSelected()) {
            success = doCopy(fileName, destFilename, edits);
        } else if (moveRadioButton.isSelected()) {
            success = doMove(fileName, destFilename, edits);
        }
    }
    if (success) {

        for (BibEntry aXmpEntriesInFile : xmpEntriesInFile) {

            aXmpEntriesInFile.setId(IdGenerator.next());
            edits.addEdit(new UndoableInsertEntry(panel.getDatabase(), aXmpEntriesInFile, panel));
            panel.getDatabase().insertEntry(aXmpEntriesInFile);
            doLink(aXmpEntriesInFile, fileType, destFilename, true, edits);

        }
        panel.markBaseChanged();
        panel.updateEntryEditorIfShowing();
    }
    return true;
}