Example usage for javax.swing JDialog dispose

List of usage examples for javax.swing JDialog dispose

Introduction

In this page you can find the example usage for javax.swing JDialog dispose.

Prototype

public void dispose() 

Source Link

Document

Releases all of the native screen resources used by this Window , its subcomponents, and all of its owned children.

Usage

From source file:interfaces.InterfazPrincipal.java

private void botonGenerarReporteClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonGenerarReporteClienteActionPerformed
    // TODO add your handling code here:
    try {//from   w  w w  . j  ava  2s  .  c o m
        if (clienteReporteClienteFechaFinal.getSelectedDate().getTime()
                .compareTo(clienteReporteClienteFechaInicial.getSelectedDate().getTime()) < 0) {
            JOptionPane.showMessageDialog(this, "La fecha final debe ser posterior al dia de inicio");
        } else {
            final ArrayList<Integer> listaIDFlujos = new ArrayList<>();
            final JDialog dialogoEditar = new JDialog();
            dialogoEditar.setTitle("Reporte cliente");
            dialogoEditar.setSize(350, 610);
            dialogoEditar.setResizable(false);

            JPanel panelDialogo = new JPanel();
            panelDialogo.setLayout(new GridBagLayout());

            GridBagConstraints c = new GridBagConstraints();
            //c.fill = GridBagConstraints.HORIZONTAL;

            JLabel ediitarTextoPrincipalDialogo = new JLabel("Informe cliente");
            c.gridx = 0;
            c.gridy = 0;
            c.gridwidth = 1;
            c.insets = new Insets(10, 45, 10, 10);
            Font textoGrande = new Font("Arial", 1, 18);
            ediitarTextoPrincipalDialogo.setFont(textoGrande);
            panelDialogo.add(ediitarTextoPrincipalDialogo, c);

            final JTable tablaDialogo = new JTable();
            DefaultTableModel modeloTabla = new DefaultTableModel() {

                @Override
                public boolean isCellEditable(int row, int column) {
                    //all cells false
                    return false;
                }
            };
            ;

            modeloTabla.addColumn("Factura");
            modeloTabla.addColumn("Tipo Flujo");
            modeloTabla.addColumn("Fecha");
            modeloTabla.addColumn("Valor");

            //Llenar tabla
            ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();
            ArrayList<String[]> flujosCliente = controladorFlujoFactura.getTodosFlujo_Factura(
                    " where factura_id in (select factura_id from Factura where cliente_id = "
                            + String.valueOf(jTextFieldIdentificacionClienteReporte.getText())
                            + ") order by factura_id");
            // {"flujo_id","factura_id","tipo_flujo","fecha","valor"};
            ArrayList<Calendar> fechasFlujos = new ArrayList<>();

            for (int i = 0; i < flujosCliente.size(); i++) {
                String fila[] = new String[4];
                String[] objeto = flujosCliente.get(i);
                fila[0] = objeto[1];
                fila[1] = objeto[2];
                fila[2] = objeto[3];
                fila[3] = objeto[4];

                //Filtrar, mirar las fechas
                String[] partirEspacios = objeto[3].split("\\s");
                //El primer string es la fecha sin hora
                //Ahora esparamos por -
                String[] tomarAgeMesDia = partirEspacios[0].split("-");

                //Realizar filtro
                int ageConsulta = Integer.parseInt(tomarAgeMesDia[0]);
                int mesConsulta = Integer.parseInt(tomarAgeMesDia[1]);
                int diaConsulta = Integer.parseInt(tomarAgeMesDia[2]);

                //Obtenemos dias, mes y ao de la consulta
                //Inicial
                int anioInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.YEAR);
                int mesInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.MONTH) + 1;
                int diaInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.DAY_OF_MONTH);
                //Final
                int anioFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.YEAR);
                int mesFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.MONTH) + 1;
                int diaFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.DAY_OF_MONTH);

                //Construir fechas
                Calendar fechaDeLaBD = new GregorianCalendar(ageConsulta, mesConsulta, diaConsulta);
                //Set year, month, day)

                Calendar fechaInicialRango = new GregorianCalendar(anioInicial, mesInicial, diaInicial);
                Calendar fechaFinalRango = new GregorianCalendar(anioFinal, mesFinal, diaFinal);

                if (fechaDeLaBD.compareTo(fechaInicialRango) <= 0
                        && fechaDeLaBD.compareTo(fechaFinalRango) >= 0) {
                    fechasFlujos.add(fechaDeLaBD);
                    modeloTabla.addRow(fila);
                }

            }

            if (modeloTabla.getRowCount() > 0) {
                tablaDialogo.setModel(modeloTabla);
                tablaDialogo.getColumn("Factura").setMinWidth(80);
                tablaDialogo.getColumn("Tipo Flujo").setMinWidth(80);
                tablaDialogo.getColumn("Fecha").setMinWidth(90);
                tablaDialogo.getColumn("Valor").setMinWidth(80);
                tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                JScrollPane scroll = new JScrollPane(tablaDialogo);
                scroll.setPreferredSize(new Dimension(330, 150));

                c.gridx = 0;
                c.gridy = 1;
                c.gridwidth = 1;
                c.insets = new Insets(0, 0, 0, 0);
                panelDialogo.add(scroll, c);

                TimeSeries localTimeSeries = new TimeSeries("Compras del cliente en el periodo");

                Map listaAbonos = new HashMap();

                for (int i = 0; i < modeloTabla.getRowCount(); i++) {
                    listaIDFlujos.add(Integer.parseInt(flujosCliente.get(i)[0]));

                    if (modeloTabla.getValueAt(i, 1).equals("abono")) {
                        Calendar fechaFlujo = fechasFlujos.get(i);
                        double valor = Double.parseDouble(String.valueOf(modeloTabla.getValueAt(i, 3)));

                        int anoDato = fechaFlujo.get(Calendar.YEAR);
                        int mesDato = fechaFlujo.get(Calendar.MONTH) + 1;
                        int diaDato = fechaFlujo.get(Calendar.DAY_OF_MONTH);
                        Day FechaDato = new Day(diaDato, mesDato, anoDato);

                        if (listaAbonos.get(FechaDato) != null) {
                            double valorAbono = (double) listaAbonos.get(FechaDato);
                            listaAbonos.remove(FechaDato);
                            listaAbonos.put(FechaDato, valorAbono + valor);
                        } else {
                            listaAbonos.put(FechaDato, valor);

                        }

                    }

                }
                Double maximo = 0.0;
                Iterator iterator = listaAbonos.keySet().iterator();
                while (iterator.hasNext()) {
                    Day key = (Day) iterator.next();
                    Double value = (double) listaAbonos.get(key);
                    maximo = Math.max(maximo, value);
                    localTimeSeries.add(key, value);
                }

                //localTimeSeries.add();
                TimeSeriesCollection datos = new TimeSeriesCollection(localTimeSeries);

                JFreeChart chart = ChartFactory.createTimeSeriesChart("Compras del cliente en el periodo", // Title
                        "Tiempo", // x-axis Label
                        "Total ($)", // y-axis Label
                        datos, // Dataset
                        true, // Show Legend
                        true, // Use tooltips
                        false // Configure chart to generate URLs?
                );
                /*Altering the graph */
                XYPlot plot = (XYPlot) chart.getPlot();
                plot.setAxisOffset(new RectangleInsets(5.0, 10.0, 10.0, 5.0));
                plot.setDomainCrosshairVisible(true);
                plot.setRangeCrosshairVisible(true);

                XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
                renderer.setBaseShapesVisible(true);
                renderer.setBaseShapesFilled(true);

                NumberAxis numberAxis = (NumberAxis) plot.getRangeAxis();
                numberAxis.setRange(new Range(0, maximo * 1.2));
                Font font = new Font("Dialog", Font.PLAIN, 9);
                numberAxis.setTickLabelFont(font);
                numberAxis.setLabelFont(font);

                DateAxis axis = (DateAxis) plot.getDomainAxis();
                axis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy"));
                axis.setAutoTickUnitSelection(false);
                axis.setVerticalTickLabels(true);

                axis.setTickLabelFont(font);
                axis.setLabelFont(font);

                LegendTitle leyendaChart = chart.getLegend();
                leyendaChart.setItemFont(font);

                Font fontTitulo = new Font("Dialog", Font.BOLD, 12);
                TextTitle tituloChart = chart.getTitle();
                tituloChart.setFont(fontTitulo);

                ChartPanel CP = new ChartPanel(chart);
                Dimension D = new Dimension(330, 300);
                CP.setPreferredSize(D);
                CP.setVisible(true);
                c.gridx = 0;
                c.gridy = 2;
                c.gridwidth = 1;
                c.insets = new Insets(10, 0, 0, 0);
                panelDialogo.add(CP, c);

                c.gridx = 0;
                c.gridy = 3;
                c.gridwidth = 1;
                c.anchor = GridBagConstraints.WEST;
                c.insets = new Insets(10, 30, 0, 0);

                JButton botonCerrar = new JButton("Cerrar");
                botonCerrar.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        dialogoEditar.dispose();
                    }
                });
                panelDialogo.add(botonCerrar, c);

                JButton botonGenerarPDF = new JButton("Guardar archivo");
                botonGenerarPDF.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        ReporteFlujosCliente reporteFlujosCliente = new ReporteFlujosCliente();
                        reporteFlujosCliente.guardarDocumentoDialogo(dialogoEditar, listaIDFlujos,
                                Integer.parseInt(jTextFieldIdentificacionClienteReporte.getText()),
                                clienteReporteClienteFechaInicial.getSelectedDate(),
                                clienteReporteClienteFechaFinal.getSelectedDate());

                    }
                });
                c.insets = new Insets(10, 100, 0, 0);

                panelDialogo.add(botonGenerarPDF, c);

                JButton botonImprimir = new JButton("Imprimir");
                botonImprimir.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        ReporteFlujosCliente reporteFlujosCliente = new ReporteFlujosCliente();
                        reporteFlujosCliente.imprimirFlujo(listaIDFlujos,
                                Integer.parseInt(jTextFieldIdentificacionClienteReporte.getText()),
                                clienteReporteClienteFechaInicial.getSelectedDate(),
                                clienteReporteClienteFechaFinal.getSelectedDate());

                    }
                });
                c.insets = new Insets(10, 230, 0, 0);

                panelDialogo.add(botonImprimir, c);
                dialogoEditar.add(panelDialogo);

                dialogoEditar.setVisible(true);

            } else {
                JOptionPane.showMessageDialog(this,
                        "El cliente no registra movimientos en el rango de fechas seleccionado");
            }

        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Debe seleccionar un da inicial y final de fechas");
    }

}

From source file:ome.formats.importer.gui.FileQueueHandler.java

/**
 * Retrieve the file chooser's selected reader then iterate over
 * each of our supplied containers filtering out those whose format
 * do not match those of the selected reader.
 * /*from  w  w  w .  j  a  va  2  s .  c  o m*/
 * @param allContainers List of ImporterContainers
 */
private void handleFiles(List<ImportContainer> allContainers) {
    FileFilter selectedFilter = fileChooser.getFileFilter();
    IFormatReader selectedReader = null;

    if (selectedFilter instanceof FormatFileFilter) {
        log.debug("Selected file filter: " + selectedFilter);
        selectedReader = ((FormatFileFilter) selectedFilter).getReader();
    }

    List<ImportContainer> containers = new ArrayList<ImportContainer>();
    for (ImportContainer ic : allContainers) {
        if (selectedReader == null) {
            // The user selected "All supported file types"
            containers = allContainers;
            break;
        }
        String a = selectedReader.getFormat();
        String b = ic.getReader();
        if (a.equals(b) || b == null) {
            containers.add(ic);
        } else {
            log.debug(String.format("Skipping %s (%s != %s)", ic.getFile().getAbsoluteFile(), a, b));
        }
    }

    Boolean spw = spwOrNull(containers);

    if (containers.size() == 0 && !candidatesFormatException) {
        final JOptionPane optionPane = new JOptionPane("\nNo importable files found in this selection.",
                JOptionPane.WARNING_MESSAGE);
        final JDialog errorDialog = new JDialog(viewer, "No Importable Files Found", true);
        errorDialog.setContentPane(optionPane);

        optionPane.addPropertyChangeListener(new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent e) {
                String prop = e.getPropertyName();

                if (errorDialog.isVisible() && (e.getSource() == optionPane)
                        && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
                    errorDialog.dispose();
                }
            }
        });

        errorDialog.toFront();
        errorDialog.pack();
        errorDialog.setLocationRelativeTo(viewer);
        errorDialog.setVisible(true);
    }

    if (candidatesFormatException) {
        viewer.candidateErrorsCollected(viewer);
        candidatesFormatException = false;
    }

    if (spw == null) {
        addEnabled(true);
        containers.clear();
        return; // Invalid containers.
    }

    if (getOMEROMetadataStoreClient() != null && spw.booleanValue()) {
        addEnabled(true);
        SPWDialog dialog = new SPWDialog(config, viewer, "Screen Import", true, getOMEROMetadataStoreClient());
        if (dialog.cancelled == true || dialog.screen == null)
            return;
        for (ImportContainer ic : containers) {
            ic.setTarget(dialog.screen);
            String title = dialog.screen.getName().getValue();
            addFileToQueue(ic, title, false, 0);
        }

        qTable.centerOnRow(qTable.getQueue().getRowCount() - 1);
        qTable.importBtn.requestFocus();

    } else if (getOMEROMetadataStoreClient() != null) {
        addEnabled(true);
        ImportDialog dialog = new ImportDialog(config, viewer, "Image Import", true,
                getOMEROMetadataStoreClient());
        if (dialog.cancelled == true || dialog.dataset == null)
            return;

        Double[] pixelSizes = new Double[] { dialog.pixelSizeX, dialog.pixelSizeY, dialog.pixelSizeZ };
        Boolean useFullPath = config.useFullPath.get();
        if (dialog.useCustomNamingChkBox.isSelected() == false)
            useFullPath = null; //use the default bio-formats naming

        for (ImportContainer ic : containers) {
            ic.setTarget(dialog.dataset);
            ic.setUserPixels(pixelSizes);
            ic.setArchive(dialog.archiveImage.isSelected());
            String title = "";
            if (dialog.project.getId() != null) {
                ic.setProjectID(dialog.project.getId().getValue());
                title = dialog.project.getName().getValue() + " / " + dialog.dataset.getName().getValue();
            } else {
                title = "none / " + dialog.dataset.getName().getValue();
            }

            addFileToQueue(ic, title, useFullPath, config.numOfDirectories.get());
        }

        qTable.centerOnRow(qTable.getQueue().getRowCount() - 1);
        qTable.importBtn.requestFocus();
    } else {
        addEnabled(true);
        JOptionPane.showMessageDialog(viewer,
                "Due to an error the application is unable to \n"
                        + "retrieve an OMEROMetadataStore and cannot continue."
                        + "The most likely cause for this error is that you"
                        + "are not logged in. Please try to login again.");
    }
}

From source file:ome.formats.importer.gui.GuiImporter.java

public void update(IObservable importLibrary, ImportEvent event) {

    // Keep alive has failed, call logout
    if (event instanceof ImportEvent.LOGGED_OUT) {
        logout();/*  www.  j  a  v a 2 s . c o m*/
        showLogoutMessage();
    }

    if (event instanceof ImportEvent.LOADING_IMAGE) {
        ImportEvent.LOADING_IMAGE ev = (ImportEvent.LOADING_IMAGE) event;

        getStatusBar().setProgress(true, -1, "Loading file " + ev.numDone + " of " + ev.total);
        appendToOutput("> [" + ev.index + "] Loading image \"" + ev.shortName + "\"...\n");
        getStatusBar().setStatusIcon("gfx/import_icon_16.png", "Prepping file \"" + ev.shortName);
    }

    else if (event instanceof ImportEvent.LOADED_IMAGE) {
        ImportEvent.LOADED_IMAGE ev = (ImportEvent.LOADED_IMAGE) event;

        getStatusBar().setProgress(true, -1, "Analyzing file " + ev.numDone + " of " + ev.total);
        appendToOutput(" Succesfully loaded.\n");
        appendToOutput("> [" + ev.index + "] Importing metadata for " + "image \"" + ev.shortName + "\"... ");
        getStatusBar().setStatusIcon("gfx/import_icon_16.png",
                "Analyzing the metadata for file \"" + ev.shortName);
    }

    else if (event instanceof ImportEvent.BEGIN_SAVE_TO_DB) {
        ImportEvent.BEGIN_SAVE_TO_DB ev = (ImportEvent.BEGIN_SAVE_TO_DB) event;
        appendToOutput("> [" + ev.index + "] Saving metadata for " + "image \"" + ev.filename + "\"... ");
        getStatusBar().setStatusIcon("gfx/import_icon_16.png", "Saving metadata for file \"" + ev.filename);
    }

    else if (event instanceof ImportEvent.DATASET_STORED) {
        ImportEvent.DATASET_STORED ev = (ImportEvent.DATASET_STORED) event;

        int num = ev.numDone;
        int tot = ev.total;
        int pro = num - 1;
        appendToOutputLn("Successfully stored to " + ev.target.getClass().getSimpleName() + " \"" + ev.filename
                + "\" with id \"" + ev.target.getId().getValue() + "\".");
        appendToOutputLn(
                "> [" + ev.series + "] Importing pixel data for " + "image \"" + ev.filename + "\"... ");
        getStatusBar().setProgress(true, 0, "Importing file " + num + " of " + tot);
        getStatusBar().setProgressValue(pro);
        getStatusBar().setStatusIcon("gfx/import_icon_16.png",
                "Importing the pixel data for file \"" + ev.filename);
        appendToOutput("> Importing plane: ");
    }

    else if (event instanceof ImportEvent.DATA_STORED) {
        ImportEvent.DATA_STORED ev = (ImportEvent.DATA_STORED) event;

        appendToOutputLn("> Successfully stored with pixels id \"" + ev.pixId + "\".");
        appendToOutputLn("> [" + ev.filename + "] Image imported successfully!");
    }

    else if (event instanceof FILE_EXCEPTION) {
        FILE_EXCEPTION ev = (FILE_EXCEPTION) event;
        if (IOException.class.isAssignableFrom(ev.exception.getClass())) {

            final JOptionPane optionPane = new JOptionPane(
                    "The importer cannot retrieve one of your images in a timely manner.\n"
                            + "The file in question is:\n'" + ev.filename + "'\n\n"
                            + "There are a number of reasons you may see this error:\n"
                            + " - The file has been deleted.\n"
                            + " - There was a networking error retrieving a remotely saved file.\n"
                            + " - An archived file has not been fully retrieved from backup.\n\n"
                            + "The importer should now continue with the remainer of your imports.\n",
                    JOptionPane.ERROR_MESSAGE);

            final JDialog dialog = new JDialog(this, "IO Error");
            dialog.setAlwaysOnTop(true);
            dialog.setContentPane(optionPane);
            dialog.pack();
            dialog.setVisible(true);
            optionPane.addPropertyChangeListener(new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent e) {
                    String prop = e.getPropertyName();

                    if (dialog.isVisible() && (e.getSource() == optionPane)
                            && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
                        dialog.dispose();
                    }
                }
            });
        }
    }

    else if (event instanceof EXCEPTION_EVENT) {
        EXCEPTION_EVENT ev = (EXCEPTION_EVENT) event;
        log.error("EXCEPTION_EVENT", ev.exception);
    }

    else if (event instanceof INTERNAL_EXCEPTION) {
        INTERNAL_EXCEPTION e = (INTERNAL_EXCEPTION) event;
        log.error("INTERNAL_EXCEPTION", e.exception);

        // What else should we do here? Why are EXCEPTION_EVENTs being
        // handled here?
    }

    else if (event instanceof ImportEvent.ERRORS_PENDING) {
        tPane.setIconAt(4, GuiCommonElements.getImageIcon(ERROR_ICON_ANIM));
        errors_pending = true;
        error_notification = true;
    }

    else if (event instanceof ImportEvent.ERRORS_COMPLETE) {
        tPane.setIconAt(4, GuiCommonElements.getImageIcon(ERROR_ICON));
        error_notification = false;
    }

    else if (event instanceof ImportEvent.ERRORS_COMPLETE) {
        tPane.setIconAt(4, GuiCommonElements.getImageIcon(ERROR_ICON));
        error_notification = false;
    }

    else if (event instanceof ImportEvent.ERRORS_FAILED) {
        sendingErrorsFailed(this);
    }

    else if (event instanceof ImportEvent.IMPORT_QUEUE_DONE && errors_pending == true) {
        errors_pending = false;
        importErrorsCollected(this);
    }

}

From source file:ome.formats.importer.gui.GuiImporter.java

/**
 * Display errors in import dialog //  w  ww.j  av  a 2s  .  c  om
 * 
 * @param frame - parent frame
 */
private void importErrorsCollected(Component frame) {
    final JOptionPane optionPane = new JOptionPane(
            "\nYour import has produced one or more errors, " + "\nvisit the 'Import Errors' tab for details.",
            JOptionPane.WARNING_MESSAGE);
    final JDialog errorDialog = new JDialog(this, "Errors Collected", false);
    errorDialog.setContentPane(optionPane);

    optionPane.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();

            if (errorDialog.isVisible() && (e.getSource() == optionPane)
                    && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
                errorDialog.dispose();
            }
        }
    });

    errorDialog.toFront();
    errorDialog.pack();
    errorDialog.setLocationRelativeTo(frame);
    errorDialog.setVisible(true);
}

From source file:ome.formats.importer.gui.GuiImporter.java

/**
 * Display errors in candidates dialog/*w w w  .ja v a  2s. c  o  m*/
 * 
 * @param frame - parent frame
 */
public void candidateErrorsCollected(Component frame) {
    errors_pending = false;
    final JOptionPane optionPane = new JOptionPane(
            "\nAdding these files to the queue has produced one or more errors and some"
                    + "\n files will not be displayed on the queue. View the 'Import Errors' tab for details.",
            JOptionPane.WARNING_MESSAGE);
    final JDialog errorDialog = new JDialog(this, "Errors Collected", true);
    errorDialog.setContentPane(optionPane);

    optionPane.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();

            if (errorDialog.isVisible() && (e.getSource() == optionPane)
                    && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
                errorDialog.dispose();
            }
        }
    });

    errorDialog.toFront();
    errorDialog.pack();
    errorDialog.setLocationRelativeTo(frame);
    errorDialog.setVisible(true);
}

From source file:ome.formats.importer.gui.GuiImporter.java

/**
 * Display failed sending errors dialog//from   ww w.  j  a  v  a 2 s  .c o  m
 * 
 * @param frame - parent frame
 */
public void sendingErrorsFailed(Component frame) {
    final JOptionPane optionPane = new JOptionPane(
            "\nDue to an error we were not able to send your error messages."
                    + "\nto our feedback server. Please try again.",
            JOptionPane.WARNING_MESSAGE);

    final JDialog failedDialog = new JDialog(this, "Feedback Failed!", true);

    failedDialog.setContentPane(optionPane);

    optionPane.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();

            if (failedDialog.isVisible() && (e.getSource() == optionPane)
                    && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
                failedDialog.dispose();
            }
        }
    });

    failedDialog.toFront();
    failedDialog.pack();
    failedDialog.setLocationRelativeTo(frame);
    failedDialog.setVisible(true);
}

From source file:ome.formats.importer.gui.ImportDialog.java

/**
 * Dialog explaining metadata limitations when changing the main dialog's naming settings
 * //from ww w  . j av a 2s.  c  om
 * @param frame - parent component
 */
public void sendNamingWarning(Component frame) {
    final JOptionPane optionPane = new JOptionPane(
            "\nNOTE: Some file formats do not include the file name in their metadata, "
                    + "\nand disabling this option may result in files being imported without a "
                    + "\nreference to their file name. For example, 'myfile.lsm [image001]' "
                    + "\nwould show up as 'image001' with this optioned turned off.",
            JOptionPane.WARNING_MESSAGE);
    final JDialog warningDialog = new JDialog(this, "Naming Warning!", true);
    warningDialog.setContentPane(optionPane);

    optionPane.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent e) {
            String prop = e.getPropertyName();

            if (warningDialog.isVisible() && (e.getSource() == optionPane)
                    && (prop.equals(JOptionPane.VALUE_PROPERTY))) {
                warningDialog.dispose();
            }
        }
    });

    warningDialog.toFront();
    warningDialog.pack();
    warningDialog.setLocationRelativeTo(frame);
    warningDialog.setVisible(true);
}

From source file:org.apache.cayenne.modeler.util.CayenneController.java

/**
 * If this view or a parent view is a JDialog, makes it closeable on ESC hit. Dialog
 * "defaultCloseOperation" property is taken into account when processing ESC button
 * click.//from  ww  w  . j  a  va  2 s.  c o m
 */
protected void makeCloseableOnEscape() {

    Window window = getWindow();
    if (!(window instanceof JDialog)) {
        return;
    }

    final JDialog dialog = (JDialog) window;

    KeyStroke escReleased = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true);
    ActionListener closeAction = new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if (dialog.isVisible()) {
                switch (dialog.getDefaultCloseOperation()) {
                case JDialog.HIDE_ON_CLOSE:
                    dialog.setVisible(false);
                    break;
                case JDialog.DISPOSE_ON_CLOSE:
                    dialog.setVisible(false);
                    dialog.dispose();
                    break;
                case JDialog.DO_NOTHING_ON_CLOSE:
                default:
                    break;
                }
            }
        }
    };
    dialog.getRootPane().registerKeyboardAction(closeAction, escReleased, JComponent.WHEN_IN_FOCUSED_WINDOW);
}

From source file:org.apache.marmotta.splash.common.ui.MessageDialog.java

public static void show(String title, String message, String description) {
    final JDialog dialog = new JDialog((Frame) null, title);
    dialog.setModal(true);/*from   www.  j  a  v  a  2  s .  c o  m*/
    dialog.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);

    final JPanel root = new JPanel(new GridBagLayout());
    root.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    dialog.getRootPane().setContentPane(root);

    final JButton close = new JButton("OK");
    close.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            dialog.setVisible(false);
        }
    });
    GridBagConstraints cClose = new GridBagConstraints();
    cClose.gridx = 0;
    cClose.gridy = 2;
    cClose.gridwidth = 2;
    cClose.weightx = 1;
    cClose.weighty = 0;
    cClose.insets = new Insets(5, 5, 5, 5);

    root.add(close, cClose);
    dialog.getRootPane().setDefaultButton(close);

    Icon icon = loadIcon(MARMOTTA_ICON);
    if (icon != null) {
        JLabel lblIcn = new JLabel(icon);

        GridBagConstraints cIcon = new GridBagConstraints();
        cIcon.gridx = 1;
        cIcon.gridy = 0;
        cIcon.gridheight = 2;
        cIcon.fill = GridBagConstraints.NONE;
        cIcon.weightx = 0;
        cIcon.weighty = 1;
        cIcon.anchor = GridBagConstraints.NORTH;
        cIcon.insets = new Insets(10, 5, 5, 0);
        root.add(lblIcn, cIcon);
    }

    JLabel lblMsg = new JLabel("<html>" + StringEscapeUtils.escapeHtml3(message).replaceAll("\\n", "<br>"));
    lblMsg.setFont(lblMsg.getFont().deriveFont(Font.BOLD, 16f));
    GridBagConstraints cLabel = new GridBagConstraints();
    cLabel.gridx = 0;
    cLabel.gridy = 0;
    cLabel.fill = GridBagConstraints.BOTH;
    cLabel.weightx = 1;
    cLabel.weighty = 0.5;
    cLabel.insets = new Insets(5, 5, 5, 5);
    root.add(lblMsg, cLabel);

    JLabel lblDescr = new JLabel(
            "<html>" + StringEscapeUtils.escapeHtml3(description).replaceAll("\\n", "<br>"));
    cLabel.gridy++;
    cLabel.insets = new Insets(0, 5, 5, 5);
    root.add(lblDescr, cLabel);

    dialog.pack();
    dialog.setLocationRelativeTo(null);

    dialog.setVisible(true);
    dialog.dispose();
}

From source file:org.apache.marmotta.splash.common.ui.SelectionDialog.java

public static int select(String title, String message, String description, List<Option> options,
        int defaultOption) {
    final JDialog dialog = new JDialog((Frame) null, title);
    dialog.setModal(true);/*from  www  .  jav a  2 s.  c o  m*/
    dialog.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);

    final AtomicInteger result = new AtomicInteger(Math.max(defaultOption, -1));

    JButton defaultBtn = null;

    final JPanel root = new JPanel(new GridBagLayout());
    root.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    dialog.getRootPane().setContentPane(root);

    JLabel lblMsg = new JLabel("<html>" + StringEscapeUtils.escapeHtml3(message).replaceAll("\\n", "<br>"));
    lblMsg.setFont(lblMsg.getFont().deriveFont(Font.BOLD, 16f));
    GridBagConstraints cLabel = new GridBagConstraints();
    cLabel.gridx = 0;
    cLabel.gridy = 0;
    cLabel.fill = GridBagConstraints.BOTH;
    cLabel.weightx = 1;
    cLabel.weighty = 0.5;
    cLabel.insets = new Insets(5, 5, 5, 5);
    root.add(lblMsg, cLabel);

    JLabel lblDescr = new JLabel(
            "<html>" + StringEscapeUtils.escapeHtml3(description).replaceAll("\\n", "<br>"));
    cLabel.gridy++;
    cLabel.insets = new Insets(0, 5, 5, 5);
    root.add(lblDescr, cLabel);

    // All the options
    cLabel.ipadx = 10;
    cLabel.ipady = 10;
    cLabel.insets = new Insets(5, 15, 0, 15);
    for (int i = 0; i < options.size(); i++) {
        cLabel.gridy++;

        final Option o = options.get(i);
        final JButton btn = new JButton(
                "<html>" + StringEscapeUtils.escapeHtml3(o.label).replaceAll("\\n", "<br>"),
                MessageDialog.loadIcon(o.icon));
        if (StringUtils.isNotBlank(o.info)) {
            btn.setToolTipText("<html>" + StringEscapeUtils.escapeHtml3(o.info).replaceAll("\\n", "<br>"));
        }

        btn.setHorizontalAlignment(AbstractButton.LEADING);
        btn.setVerticalTextPosition(AbstractButton.CENTER);
        btn.setHorizontalTextPosition(AbstractButton.TRAILING);

        final int myAnswer = i;
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                result.set(myAnswer);
                dialog.setVisible(false);
            }
        });

        root.add(btn, cLabel);
        if (i == defaultOption) {
            dialog.getRootPane().setDefaultButton(btn);
            defaultBtn = btn;
        }
    }

    final Icon icon = MessageDialog.loadIcon();
    if (icon != null) {
        JLabel lblIcn = new JLabel(icon);

        GridBagConstraints cIcon = new GridBagConstraints();
        cIcon.gridx = 1;
        cIcon.gridy = 0;
        cIcon.gridheight = 2 + options.size();
        cIcon.fill = GridBagConstraints.NONE;
        cIcon.weightx = 0;
        cIcon.weighty = 1;
        cIcon.anchor = GridBagConstraints.NORTH;
        cIcon.insets = new Insets(10, 5, 5, 0);
        root.add(lblIcn, cIcon);
    }

    final JButton close = new JButton("Cancel");
    close.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            result.set(-1);
            dialog.setVisible(false);
        }
    });
    GridBagConstraints cClose = new GridBagConstraints();
    cClose.gridx = 0;
    cClose.gridy = 2 + options.size();
    cClose.gridwidth = 2;
    cClose.weightx = 1;
    cClose.weighty = 0;
    cClose.insets = new Insets(15, 5, 5, 5);

    root.add(close, cClose);
    if (defaultOption < 0) {
        dialog.getRootPane().setDefaultButton(close);
        defaultBtn = close;
    }

    dialog.pack();
    dialog.setLocationRelativeTo(null);
    defaultBtn.requestFocusInWindow();

    dialog.setVisible(true);
    dialog.dispose();

    return result.get();
}