Example usage for javax.swing JOptionPane YES_NO_OPTION

List of usage examples for javax.swing JOptionPane YES_NO_OPTION

Introduction

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

Prototype

int YES_NO_OPTION

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

Click Source Link

Document

Type used for showConfirmDialog.

Usage

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

@Override
public void run() {
    BasePanel panel = frame.getCurrentBasePanel();
    if (panel == null) {
        return;/*w  ww  .  ja va  2s  . c o m*/
    }
    if (panel.getSelectedEntries().isEmpty()) {
        message = Localization.lang("This operation requires one or more entries to be selected.");
        getCallBack().update();
        return;
    }

    List<IExportFormat> exportFormats = new LinkedList<>(ExportFormats.getExportFormats().values());
    Collections.sort(exportFormats, (e1, e2) -> e1.getDisplayName().compareTo(e2.getDisplayName()));
    String[] exportFormatDisplayNames = new String[exportFormats.size()];
    for (int i = 0; i < exportFormats.size(); i++) {
        IExportFormat exportFormat = exportFormats.get(i);
        exportFormatDisplayNames[i] = exportFormat.getDisplayName();
    }

    JList<String> list = new JList<>(exportFormatDisplayNames);
    list.setBorder(BorderFactory.createEtchedBorder());
    list.setSelectionInterval(0, 0);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    int answer = JOptionPane.showOptionDialog(frame, list, Localization.lang("Select export format"),
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[] {
                    Localization.lang("Export with selected format"), Localization.lang("Return to JabRef") },
            Localization.lang("Export with selected format"));
    if (answer == JOptionPane.NO_OPTION) {
        return;
    }

    IExportFormat format = exportFormats.get(list.getSelectedIndex());

    // Set the global variable for this database's file directory before exporting,
    // so formatters can resolve linked files correctly.
    // (This is an ugly hack!)
    Globals.prefs.fileDirForDatabase = frame.getCurrentBasePanel().getBibDatabaseContext().getFileDirectory();

    File tmp = null;
    try {
        // To simplify the exporter API we simply do a normal export to a temporary
        // file, and read the contents afterwards:
        tmp = File.createTempFile("jabrefCb", ".tmp");
        tmp.deleteOnExit();
        List<BibEntry> entries = panel.getSelectedEntries();

        // Write to file:
        format.performExport(panel.getBibDatabaseContext(), tmp.getPath(), panel.getEncoding(), entries);
        // Read the file and put the contents on the clipboard:
        StringBuilder sb = new StringBuilder();
        try (Reader reader = new InputStreamReader(new FileInputStream(tmp), panel.getEncoding())) {
            int s;
            while ((s = reader.read()) != -1) {
                sb.append((char) s);
            }
        }
        ClipboardOwner owner = (clipboard, content) -> {
            // Do nothing
        };
        RtfSelection rs = new RtfSelection(sb.toString());
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(rs, owner);
        message = Localization.lang("Entries exported to clipboard") + ": " + entries.size();

    } catch (Exception e) {
        LOGGER.error("Error exporting to clipboard", e); //To change body of catch statement use File | Settings | File Templates.
        message = Localization.lang("Error exporting to clipboard");
    } finally {
        // Clean up:
        if ((tmp != null) && !tmp.delete()) {
            LOGGER.info("Cannot delete temporary clipboard file");
        }
    }
}

From source file:serial.ChartFromSerial.java

/**
 * Creates new form JavaArduinoInterfacingAttempt
 *///from w  w w. j a  v a  2s  . com
public ChartFromSerial() {
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        System.out.println(e);
    }
    initComponents();

    //set autoscroll
    autoScroll_chkBx.setSelected(true);
    autoScrollEnabled = true;

    //create the graph
    defaultSeries = new XYSeries(graphName);
    defaultDataset = new XYSeriesCollection(defaultSeries);
    defaultChart = ChartFactory.createXYLineChart(graphName, xAxisLabel, yAxisLabel, defaultDataset);
    graph = new ChartPanel(defaultChart);
    chartPanel.add(graph, BorderLayout.CENTER);
    graph.setVisible(true);

    //create the text log
    text = new JTextArea();
    text.setEditable(false);
    textScrollPane = new JScrollPane(text);
    textScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    textPanel.add(textScrollPane, BorderLayout.CENTER);
    textScrollPane.setVisible(true);

    //Populate the combo box
    portNames = SerialPort.getCommPorts();
    while (portNames.length == 0) {
        if (JOptionPane.showConfirmDialog(rootPane, "No connected devices found.\nWould you like to refresh?",
                "Could not connect to any devices.", JOptionPane.YES_NO_OPTION,
                JOptionPane.ERROR_MESSAGE) == JOptionPane.NO_OPTION) {
            buttonsOff();
            return;
        } else {
            portNames = SerialPort.getCommPorts();
        }
    }
    portList_jCombo.removeAllItems();
    for (SerialPort portName : portNames) {
        portList_jCombo.addItem(portName.getSystemPortName());
    }
}

From source file:br.com.colmeiatecnologia.EmailMarketing.model.ThreadEnviaEmail.java

@Override
public void run() {
    int contadorEnvios = 0;

    while (contadorEnvios <= remetente.getMaximoEnvio()) {
        while (!remetente.getDestinatarios().isEmpty()) {
            if (contadorEnvios >= remetente.getMaximoEnvio())
                break;

            EmailModel remetenteAtual = (EmailModel) remetente.getDestinatarios().toArray()[0];

            try {
                enviaEmail(remetenteAtual);
                this.sucessos++;
            } catch (Exception e) {
                this.falhas++;
                this.emailsNaoEnviados = emailsNaoEnviados + remetenteAtual.getEmail() + "\n";
            }// w ww . j  a  v a 2 s.c  o  m

            //Apaga destinatario atual da lista de destinatrios
            remetente.getDestinatarios().remove(remetente.getDestinatarios().toArray()[0]);

            estatisticas.atualizaTela(this.sucessos, this.falhas, this.emailsNaoEnviados);

            contadorEnvios++;
        }

        contadorEnvios++;
    }

    if (remetente.getDestinatarios().isEmpty()) {
        this.cancel();
        JOptionPane.showMessageDialog(estatisticas, "O envio do email marketing foi finalizado", "Finalizado",
                JOptionPane.INFORMATION_MESSAGE);

        if (falhas > 0) {
            Object[] options = { "No", "Sim" };
            int n = JOptionPane.showOptionDialog(null, "Deseja reenviar os emails que nao foram enviados?",
                    "Falha ao enviar alguns emails", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
                    null, options, options[1]);

            //Enviar novamente
            if (n == 1) {
                janelaPrincipal.reenvia(this.remetente, this.mensagem, this.emailsNaoEnviados);
            }
        }

        estatisticas.dispose();
    }
}

From source file:br.org.acessobrasil.silvinha.util.versoes.AtualizadorDeVersoes.java

public boolean confirmarAtualizacao() {
    String msg = TradAtualizadorDeVersoes.HA_NOVA_VERSAO + TradAtualizadorDeVersoes.ASES_NOME
            + TradAtualizadorDeVersoes.DESEJA_ATUALIZAR;
    if (JOptionPane.showConfirmDialog(null, msg, TradAtualizadorDeVersoes.ATUALIZACAO_PROGRAMA,
            JOptionPane.YES_NO_OPTION) == 0) {
        return baixarVersao();
    } else {//from  w w  w  .j  av  a  2s .co m
        return false;
    }
}

From source file:net.sf.jabref.gui.exporter.ExportToClipboardAction.java

@Override
public void run() {
    BasePanel panel = frame.getCurrentBasePanel();
    if (panel == null) {
        return;//from  w ww.  ja  v a  2  s  .co m
    }
    if (panel.getSelectedEntries().isEmpty()) {
        message = Localization.lang("This operation requires one or more entries to be selected.");
        getCallBack().update();
        return;
    }

    List<IExportFormat> exportFormats = new LinkedList<>(ExportFormats.getExportFormats().values());
    Collections.sort(exportFormats, (e1, e2) -> e1.getDisplayName().compareTo(e2.getDisplayName()));
    String[] exportFormatDisplayNames = new String[exportFormats.size()];
    for (int i = 0; i < exportFormats.size(); i++) {
        IExportFormat exportFormat = exportFormats.get(i);
        exportFormatDisplayNames[i] = exportFormat.getDisplayName();
    }

    JList<String> list = new JList<>(exportFormatDisplayNames);
    list.setBorder(BorderFactory.createEtchedBorder());
    list.setSelectionInterval(0, 0);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    int answer = JOptionPane.showOptionDialog(frame, list, Localization.lang("Select export format"),
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[] {
                    Localization.lang("Export with selected format"), Localization.lang("Return to JabRef") },
            Localization.lang("Export with selected format"));
    if (answer == JOptionPane.NO_OPTION) {
        return;
    }

    IExportFormat format = exportFormats.get(list.getSelectedIndex());

    // Set the global variable for this database's file directory before exporting,
    // so formatters can resolve linked files correctly.
    // (This is an ugly hack!)
    Globals.prefs.fileDirForDatabase = frame.getCurrentBasePanel().getBibDatabaseContext().getFileDirectory();

    File tmp = null;
    try {
        // To simplify the exporter API we simply do a normal export to a temporary
        // file, and read the contents afterwards:
        tmp = File.createTempFile("jabrefCb", ".tmp");
        tmp.deleteOnExit();
        List<BibEntry> entries = panel.getSelectedEntries();

        // Write to file:
        format.performExport(panel.getBibDatabaseContext(), tmp.getPath(),
                panel.getBibDatabaseContext().getMetaData().getEncoding(), entries);
        // Read the file and put the contents on the clipboard:
        StringBuilder sb = new StringBuilder();
        try (Reader reader = new InputStreamReader(new FileInputStream(tmp),
                panel.getBibDatabaseContext().getMetaData().getEncoding())) {
            int s;
            while ((s = reader.read()) != -1) {
                sb.append((char) s);
            }
        }
        ClipboardOwner owner = (clipboard, content) -> {
            // Do nothing
        };
        RtfSelection rs = new RtfSelection(sb.toString());
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(rs, owner);
        message = Localization.lang("Entries exported to clipboard") + ": " + entries.size();

    } catch (Exception e) {
        LOGGER.error("Error exporting to clipboard", e); //To change body of catch statement use File | Settings | File Templates.
        message = Localization.lang("Error exporting to clipboard");
    } finally {
        // Clean up:
        if ((tmp != null) && !tmp.delete()) {
            LOGGER.info("Cannot delete temporary clipboard file");
        }
    }
}

From source file:com.aw.swing.mvp.ui.msg.MessageDisplayerImpl.java

public static boolean showConfirmMessage(Component parentContainer, String messageConfirm) {
    ProcessMsgBlocker.instance().removeMessage();
    int result = JOptionPane.showConfirmDialog(parentContainer, messageConfirm, GENERIC_MESSAGE_TITLE,
            JOptionPane.YES_NO_OPTION);
    return (result == JOptionPane.YES_OPTION);
}

From source file:Listeners.MyActionListener.java

@Override
public void actionPerformed(ActionEvent e) {
    switch (button.getName()) {
    case "abrir":
        getIListasRequest();/* www  . ja  v  a 2s  .c  om*/
        break;
    case "eliminar":
        int n = JOptionPane.showConfirmDialog(vista,
                "Eliminar " + lista.getItems().get(list.getSelectedIndex()).getDescripcion() + "?",
                "Eliminar", JOptionPane.YES_NO_OPTION);
        if (n == 0) {
            lista.getItems_deleted().add(lista.getItems().get(list.getSelectedIndex()));
            lista.getItems().remove(list.getSelectedIndex());

        }
        System.out.println("n" + n);
        list.setListData(lista.getItems().toArray());
        break;
    case "anadir":
        addAction();
        break;
    case "delete":
        break;
    case "editar":
        editAction();
        break;
    case "sync":
        System.out.println("pulsado sync");
        break;
    case "guardar":
        saveAction();
        break;
    case "nuevo":
        lista.setCod(0);
        vista.getNomLista().setText("Lista sin nombre");
        lista.getItems().clear();
        lista.getItems_deleted().clear();
        list.setListData(lista.getItems().toArray());
        break;
    case "aceptarAdd":
        if (!validateAddAction(add.getNombre()))
            JOptionPane.showMessageDialog(add, "Debes insertar el nombre del producto", "Ops!",
                    JOptionPane.WARNING_MESSAGE);
        else {
            System.out.println(add.getNombre().getText() + "  " + add.getCantidad().getSelectedItem());
            lista.addItem(new Item(add.getNombre().getText(),
                    Integer.parseInt((String) add.getCantidad().getSelectedItem()), 0));
            list.setListData(lista.getItems().toArray());
            add.dispose();
        }
        break;
    case "aceptarEdit":
        if (!validateEditAction(edit.getNombre()))
            JOptionPane.showMessageDialog(add, "Debes insertar el nombre del producto", "Ops!",
                    JOptionPane.WARNING_MESSAGE);
        else {
            int new_check;
            if (edit.getCheck().isSelected())
                new_check = 1;
            else
                new_check = 0;
            if (old_cant != Integer.parseInt((String) edit.getCantidad().getSelectedItem())
                    || old_check != new_check || old_name != edit.getNombre().getText()) {
                lista.getItems().get(index).setCambiado(true);
                lista.getItems().get(index).setCheck_item(new_check);
                lista.getItems().get(index)
                        .setCantidad(Integer.parseInt((String) edit.getCantidad().getSelectedItem()));
                lista.getItems().get(index).setDescripcion(edit.getNombre().getText());
                list.setListData(lista.getItems().toArray());
                lista.setModificada(true);
            }
            edit.dispose();
        }
        break;
    case "aceptarOpen":
        int cod = open.getListas().getSelectedIndex();
        getItemsListaRequest(openLists.get(cod).getCod(), openLists.get(cod).getDescripcion());
        break;
    }

}

From source file:SwingThreadingWait.java

public void actionPerformed(ActionEvent e) {
    start = System.currentTimeMillis();
    new Thread(new Runnable() {
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }/*from ww w . j a v a  2 s. c  om*/

                final int elapsed = (int) ((System.currentTimeMillis() - start) / 1000);
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        counter.setText("Time elapsed: " + elapsed + "s");
                    }
                });

                if (elapsed == 4) {
                    try {
                        final int[] answer = new int[1];
                        SwingUtilities.invokeAndWait(new Runnable() {
                            public void run() {
                                answer[0] = JOptionPane.showConfirmDialog(SwingThreadingWait.this,
                                        "Abort long operation?", "Abort?", JOptionPane.YES_NO_OPTION);
                            }
                        });
                        if (answer[0] == JOptionPane.YES_OPTION) {
                            return;
                        }
                    } catch (InterruptedException e1) {
                    } catch (InvocationTargetException e1) {
                    }
                }
            }
        }
    }).start();
}

From source file:com.qspin.qtaste.testapi.impl.generic.UtilityImpl.java

@Override
public boolean getUserConfirmation(final String title, final String message) throws QTasteException {
    final MutableBoolean confirmed = new MutableBoolean();
    try {/* w w  w . j  a va2s  . com*/
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                int result = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
                confirmed.setValue(result == JOptionPane.YES_OPTION);
            }
        });
    } catch (Exception e) {
        throw new QTasteException("Error while showing user confirmation dialog", e);
    }
    return confirmed.booleanValue();
}

From source file:com.nubits.nubot.launch.toolkit.LaunchUI.java

private String askUser() {
    //Create Options for option dialog
    String path = "";

    // Set cross-platform Java L&F (also called "Metal")
    try {//from  w ww  .  jav a 2s .co m
        UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());

        final ImageIcon icon = new ImageIcon(local_path + "/" + ICON_PATH);

        //Ask the user to ask for scratch
        Object[] options = { "Import existing JSON option file", "Configure the bot from scratch" };

        int n = JOptionPane.showOptionDialog(new JFrame(), "Chose one of the following options:",
                "NuBot UI Launcher", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, icon, //do not use a custom Icon
                options, //the titles of buttons
                options[0]); //default button title

        if (n == JOptionPane.YES_OPTION) {

            //Prompt user to chose a file.
            JFileChooser fileChooser = createFileChoser();

            int result = fileChooser.showOpenDialog(new JFrame());
            if (result == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                path = selectedFile.getAbsolutePath();
                LOG.info("Option file selected : " + path);
            } else {
                LOG.info("Closing Launch UI utility.");
                System.exit(0);
            }
        }
    } catch (ClassNotFoundException | UnsupportedLookAndFeelException | IllegalAccessException
            | InstantiationException e) {
        LOG.error(e.toString());
    }

    return path;
}