Example usage for javax.swing JDialog JDialog

List of usage examples for javax.swing JDialog JDialog

Introduction

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

Prototype

public JDialog(Window owner, String title) 

Source Link

Document

Creates a modeless dialog with the specified title and owner Window .

Usage

From source file:de.whiledo.iliasdownloader2.swing.service.MainController.java

@SuppressWarnings("unchecked")
protected void changeLookAndFeel() {
    final JDialog dialog = new JDialog(mainFrame, "Design ndern");
    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

    Collection<TwoObjectsX<String, String>> lookAndFeels = FunctionsX.asList(
            new TwoObjectsX<String, String>("Metal", UIManager.getCrossPlatformLookAndFeelClassName()),
            new TwoObjectsX<String, String>("Betriebssystem Standard",
                    UIManager.getSystemLookAndFeelClassName()),
            new TwoObjectsX<String, String>("Nimbus", NimbusLookAndFeel.class.getName()));

    dialog.setLayout(new GridLayout(0, 1));
    ButtonGroup b = new ButtonGroup();
    for (final TwoObjectsX<String, String> lookAndFeel : lookAndFeels) {
        JRadioButton rb = new JRadioButton(lookAndFeel.getObjectA());
        if (iliasProperties.getLookAndFeel().equals(lookAndFeel.getObjectB())) {
            rb.setSelected(true);/* w w w. j  a  v a2 s.  c  o m*/
        }
        rb.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    UIManager.setLookAndFeel(lookAndFeel.getObjectB());
                    iliasProperties.setLookAndFeel(lookAndFeel.getObjectB());
                    saveProperties(iliasProperties);
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                        | UnsupportedLookAndFeelException e1) {
                    showError("Fehler beim ndern des Designs", e1);
                }
                SwingUtilities.updateComponentTreeUI(mainFrame);
                SwingUtilities.updateComponentTreeUI(dialog);

            }
        });
        b.add(rb);
        dialog.add(rb);
    }

    dialog.pack();
    dialog.setLocationRelativeTo(mainFrame);
    dialog.setVisible(true);

}

From source file:jeplus.JEPlusFrameMain.java

private void jMenuItemMemoryUsageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemMemoryUsageActionPerformed
    JDialog dialog = new JDialog((JFrame) null, "Memory Usage");
    JPanel_MemoryUsage panel = new JPanel_MemoryUsage("./");
    dialog.getContentPane().add(panel);/*  w  ww  . jav a2 s  .c o m*/
    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    dialog.setSize(550, 350);
    dialog.addWindowListener(panel);
    dialog.setLocationRelativeTo(this);
    dialog.setVisible(true);
}

From source file:nick.gaImageRecognitionGui.panel.JPanelTraining.java

private void jButtonTrainActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonTrainActionPerformed

    IApiTrainer trainer = initTrainer();

    saveSettings();/*from  w w w  .  j  a  v a 2s  .c  o  m*/

    JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
    final JDialog frame = new JDialog(topFrame, false);
    JPanelTrainingInProgress trainingPanel = new JPanelTrainingInProgress(trainer);
    frame.getContentPane().add(trainingPanel);
    frame.pack();
    Util.centreWindow(frame);
    frame.setVisible(true);

}

From source file:nick.gaImageRecognitionGui.panel.JPanelTraining.java

private void jButtonSetTrainingRulesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSetTrainingRulesActionPerformed

    JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
    final JDialog frame = new JDialog(topFrame, true);
    JPanelSetTrainingRules setTrainingrules = new JPanelSetTrainingRules(trainingRules);
    frame.getContentPane().add(setTrainingrules);
    frame.pack();/*w  ww .j  ava  2s  . com*/
    Util.centreWindow(frame);
    frame.setVisible(true);

}

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

@SuppressWarnings("unchecked")
public void update(IObservable observable, ImportEvent event) {
    final OMEROMetadataStoreClient store = viewer.getLoginHandler().getMetadataStore();

    if (event instanceof ome.formats.importer.util.ErrorHandler.EXCEPTION_EVENT) {
        viewer.getErrorHandler().update(observable, event);

        if (event instanceof ome.formats.importer.util.ErrorHandler.UNKNOWN_FORMAT
                && fileChooser.getSelectedFiles().length == 1 && fileChooser.getSelectedFile().isFile()) {
            JOptionPane.showMessageDialog(viewer,
                    "This file's format is not recognized. \n" + "Perhaps the file is damaged?",
                    "Unknown Format", JOptionPane.WARNING_MESSAGE);
        }//from w ww .java  2  s.c  o  m

        if (event instanceof ome.formats.importer.util.ErrorHandler.FILE_EXCEPTION) {
            candidatesFormatException = true;
        }
    }

    if (event instanceof ome.formats.importer.util.ErrorHandler.MISSING_LIBRARY) {
        JOptionPane.showMessageDialog(viewer, "You appear to be missing a required library needed for \n"
                + "this file import. See the debug log messages for details.");
    }

    else if (event instanceof ImportCandidates.SCANNING) {
        addEnabled(false);

        ImportCandidates.SCANNING ev = (ImportCandidates.SCANNING) event;
        if (scanEx.isShutdown() || cancelScan) {
            log.info("Cancelling scan");
            ev.cancel();
            cancelScan = false;
        }

        if (ev.totalFiles < 0) {
            if (progressDialog == null) {
                double layoutTable[][] = { { 10, 180, 100, 10 }, // columns
                        { 5, 20, 5, 30, 5 } }; // rows

                progressDialog = new JDialog(viewer, "Processing Files");
                progressDialog.setSize(300, 90);
                progressDialog.setLocationRelativeTo(viewer);
                TableLayout layout = new TableLayout(layoutTable);
                progressDialog.setLayout(layout);
                directoryProgressBar = new JProgressBar();
                directoryProgressBar.setString("Please wait.");
                directoryProgressBar.setStringPainted(true);
                directoryProgressBar.setIndeterminate(true);
                progressDialog.add(directoryProgressBar, "1,1,2,1");
                JButton cancelBtn = new JButton("Cancel");

                progressDialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

                cancelBtn.addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent event) {
                        cancelScan = true;
                        progressDialog.dispose();
                        progressDialog = null;
                        addEnabled(true);
                    }
                });

                progressDialog.add(cancelBtn, "2,3,R,C");
                progressDialog.getRootPane().setDefaultButton(cancelBtn);
                progressDialog.setVisible(true);
                progressDialog.toFront();
            }
        } else {
            if (progressDialog != null) {
                updateProgress(ev.totalFiles, ev.numFiles);
            }

            if (ev.totalFiles == ev.numFiles && progressDialog != null) {
                progressDialog.dispose();
                progressDialog = null;
                addEnabled(true);
            }
        }

        viewer.appendToOutput(
                "Processing files: Scanned " + ev.numFiles + " of " + ev.totalFiles + " total.\n");

        log.debug(ev.toLog());

    }

    else if (event instanceof ImportEvent.REIMPORT) {

        String objectName = "", projectName = "", fileName = "";
        Long objectID = 0L, projectID = 0L;
        File file = null;
        Integer finalCount = 0;
        IObject object;

        int[] selectedRows = null;

        if (historyTable != null)
            selectedRows = historyTable.eTable.getSelectedRows();

        for (int r : selectedRows) {
            Vector row = new Vector();

            objectID = (Long) historyTable.table.getValueAt(r, 5);
            projectID = (Long) historyTable.table.getValueAt(r, 6);

            fileName = (String) historyTable.table.getValueAt(r, 0);
            file = new File((String) historyTable.table.getValueAt(r, 4));

            if (projectID == null || projectID == 0) {
                object = null;

                try {
                    object = store.getTarget(Screen.class, objectID);
                    objectName = ((Screen) object).getName().getValue();
                } catch (Exception e) {
                    log.warn("Failed to retrieve screen: " + objectID, e);
                    continue;
                }
            } else {
                object = null;
                try {
                    object = store.getTarget(Dataset.class, objectID);
                    objectName = ((Dataset) object).getName().getValue();
                } catch (Exception e) {
                    log.warn("Failed to retrieve dataset: " + objectID, e);
                    continue;
                }

                try {
                    projectName = store.getProject(projectID).getName().getValue();
                } catch (Exception e) {
                    log.warn("Failed to retrieve project: " + projectID, e);
                    continue;
                }
            }

            // TODO: The 6th parameter should be 'format', not 'fileName'!
            ImportContainer container = new ImportContainer(file, projectID, object, cancelScan, null, fileName,
                    null, cancelScan);

            finalCount = finalCount + 1;

            Double[] pixelSizes = new Double[] { 1.0, 1.0, 1.0 };

            row.add(fileName);
            if (projectID == null || projectID == 0) {
                row.add(objectName);
            } else {
                row.add(projectName + "/" + objectName);
            }
            // WHY ISN'T THIS CODE USING addFiletoQueue?!!?
            row.add("added");
            row.add(container);
            row.add(file);
            row.add(false);
            row.add(projectID);
            row.add(pixelSizes);
            qTable.getTable().addRow(row);
        }

        if (finalCount == 0) {
            JOptionPane.showMessageDialog(viewer,
                    "None of the images in this history\n" + "list can be reimported.");
        } else if (finalCount == 1) {
            JOptionPane.showMessageDialog(viewer, "One of the images in this history list has been\n"
                    + "re-added to the import queue for reimport.");
        } else if (finalCount > 1) {
            JOptionPane.showMessageDialog(viewer,
                    finalCount + " images in this history list have been re-added\n"
                            + "to the import queue for reimport.");
        }

        if (qTable.getTable().getRowCount() > 0)
            qTable.importBtn.setEnabled(true);
        qTable.importBtn.doClick();
    }
}

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 .java  2 s  . c  om
        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:org.apache.log4j.chainsaw.LogUI.java

/**
 * Displays a dialog which will provide options for selecting a configuration
 *//*from   w ww . j a  v a2  s .c om*/
private void showReceiverConfigurationPanel() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            final JDialog dialog = new JDialog(LogUI.this, true);
            dialog.setTitle("Load events into Chainsaw");
            dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

            dialog.setResizable(false);

            receiverConfigurationPanel.setCompletionActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    dialog.setVisible(false);

                    if (receiverConfigurationPanel.getModel().isCancelled()) {
                        return;
                    }
                    applicationPreferenceModel
                            .setShowNoReceiverWarning(!receiverConfigurationPanel.isDontWarnMeAgain());
                    //remove existing plugins
                    List plugins = pluginRegistry.getPlugins();
                    for (Iterator iter = plugins.iterator(); iter.hasNext();) {
                        Plugin plugin = (Plugin) iter.next();
                        //don't stop ZeroConfPlugin if it is registered
                        if (!plugin.getName().toLowerCase(Locale.ENGLISH).contains("zeroconf")) {
                            pluginRegistry.stopPlugin(plugin.getName());
                        }
                    }
                    URL configURL = null;

                    if (receiverConfigurationPanel.getModel().isNetworkReceiverMode()) {
                        int port = receiverConfigurationPanel.getModel().getNetworkReceiverPort();

                        try {
                            Class receiverClass = receiverConfigurationPanel.getModel()
                                    .getNetworkReceiverClass();
                            Receiver networkReceiver = (Receiver) receiverClass.newInstance();
                            networkReceiver.setName(receiverClass.getSimpleName() + "-" + port);

                            Method portMethod = networkReceiver.getClass().getMethod("setPort",
                                    new Class[] { int.class });
                            portMethod.invoke(networkReceiver, new Object[] { new Integer(port) });

                            networkReceiver.setThreshold(Level.TRACE);

                            pluginRegistry.addPlugin(networkReceiver);
                            networkReceiver.activateOptions();
                            receiversPanel.updateReceiverTreeInDispatchThread();
                        } catch (Exception e3) {
                            MessageCenter.getInstance().getLogger().error("Error creating Receiver", e3);
                            MessageCenter.getInstance().getLogger()
                                    .info("An error occurred creating your Receiver");
                        }
                    } else if (receiverConfigurationPanel.getModel().isLog4jConfig()) {
                        File log4jConfigFile = receiverConfigurationPanel.getModel().getLog4jConfigFile();
                        if (log4jConfigFile != null) {
                            try {
                                Map entries = LogFilePatternLayoutBuilder
                                        .getAppenderConfiguration(log4jConfigFile);
                                for (Iterator iter = entries.entrySet().iterator(); iter.hasNext();) {
                                    try {
                                        Map.Entry entry = (Map.Entry) iter.next();
                                        String name = (String) entry.getKey();
                                        Map values = (Map) entry.getValue();
                                        //values: conversion, file
                                        String conversionPattern = values.get("conversion").toString();
                                        File file = new File(values.get("file").toString());
                                        URL fileURL = file.toURI().toURL();
                                        String timestampFormat = LogFilePatternLayoutBuilder
                                                .getTimeStampFormat(conversionPattern);
                                        String receiverPattern = LogFilePatternLayoutBuilder
                                                .getLogFormatFromPatternLayout(conversionPattern);
                                        VFSLogFilePatternReceiver fileReceiver = new VFSLogFilePatternReceiver();
                                        fileReceiver.setName(name);
                                        fileReceiver.setAutoReconnect(true);
                                        fileReceiver.setContainer(LogUI.this);
                                        fileReceiver.setAppendNonMatches(true);
                                        fileReceiver.setFileURL(fileURL.toURI().toString());
                                        fileReceiver.setTailing(true);
                                        fileReceiver.setLogFormat(receiverPattern);
                                        fileReceiver.setTimestampFormat(timestampFormat);
                                        fileReceiver.setThreshold(Level.TRACE);
                                        pluginRegistry.addPlugin(fileReceiver);
                                        fileReceiver.activateOptions();
                                        receiversPanel.updateReceiverTreeInDispatchThread();
                                    } catch (URISyntaxException e1) {
                                        e1.printStackTrace();
                                    }
                                }
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                        }
                    } else if (receiverConfigurationPanel.getModel().isLoadConfig()) {
                        configURL = receiverConfigurationPanel.getModel().getConfigToLoad();
                    } else if (receiverConfigurationPanel.getModel().isLogFileReceiverConfig()) {
                        try {
                            URL fileURL = receiverConfigurationPanel.getModel().getLogFileURL();
                            if (fileURL != null) {
                                VFSLogFilePatternReceiver fileReceiver = new VFSLogFilePatternReceiver();
                                fileReceiver.setName(fileURL.getFile());
                                fileReceiver.setAutoReconnect(true);
                                fileReceiver.setContainer(LogUI.this);
                                fileReceiver.setAppendNonMatches(true);
                                fileReceiver.setFileURL(fileURL.toURI().toString());
                                fileReceiver.setTailing(true);
                                if (receiverConfigurationPanel.getModel().isPatternLayoutLogFormat()) {
                                    fileReceiver.setLogFormat(
                                            LogFilePatternLayoutBuilder.getLogFormatFromPatternLayout(
                                                    receiverConfigurationPanel.getModel().getLogFormat()));
                                } else {
                                    fileReceiver
                                            .setLogFormat(receiverConfigurationPanel.getModel().getLogFormat());
                                }
                                fileReceiver.setTimestampFormat(
                                        receiverConfigurationPanel.getModel().getLogFormatTimestampFormat());
                                fileReceiver.setThreshold(Level.TRACE);

                                pluginRegistry.addPlugin(fileReceiver);
                                fileReceiver.activateOptions();
                                receiversPanel.updateReceiverTreeInDispatchThread();
                            }
                        } catch (Exception e2) {
                            MessageCenter.getInstance().getLogger().error("Error creating Receiver", e2);
                            MessageCenter.getInstance().getLogger()
                                    .info("An error occurred creating your Receiver");
                        }
                    }
                    if (configURL == null && receiverConfigurationPanel.isDontWarnMeAgain()) {
                        //use the saved config file as the config URL if defined
                        if (receiverConfigurationPanel.getModel().getSaveConfigFile() != null) {
                            try {
                                configURL = receiverConfigurationPanel.getModel().getSaveConfigFile().toURI()
                                        .toURL();
                            } catch (MalformedURLException e1) {
                                e1.printStackTrace();
                            }
                        } else {
                            //no saved config defined but don't warn me is checked - use default config
                            configURL = receiverConfigurationPanel.getModel().getDefaultConfigFileURL();
                        }
                    }
                    if (configURL != null) {
                        MessageCenter.getInstance().getLogger()
                                .debug("Initialiazing Log4j with " + configURL.toExternalForm());
                        final URL finalURL = configURL;
                        new Thread(new Runnable() {
                            public void run() {
                                if (receiverConfigurationPanel.isDontWarnMeAgain()) {
                                    applicationPreferenceModel.setConfigurationURL(finalURL.toExternalForm());
                                } else {
                                    try {
                                        if (new File(finalURL.toURI()).exists()) {
                                            loadConfigurationUsingPluginClassLoader(finalURL);
                                        }
                                    } catch (URISyntaxException e) {
                                        //ignore
                                    }
                                }

                                receiversPanel.updateReceiverTreeInDispatchThread();
                            }
                        }).start();
                    }
                    File saveConfigFile = receiverConfigurationPanel.getModel().getSaveConfigFile();
                    if (saveConfigFile != null) {
                        ReceiversHelper.getInstance().saveReceiverConfiguration(saveConfigFile);
                    }
                }
            });

            receiverConfigurationPanel.setDialog(dialog);
            dialog.getContentPane().add(receiverConfigurationPanel);

            dialog.pack();

            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            dialog.setLocation((screenSize.width / 2) - (dialog.getWidth() / 2),
                    (screenSize.height / 2) - (dialog.getHeight() / 2));

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

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   w ww . j  a  v  a2  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);//ww w.  j  ava  2  s .c om
    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();
}

From source file:org.apache.tika.gui.TikaGUI.java

private void handleError(String name, Throwable t) {
    StringWriter writer = new StringWriter();
    writer.append("Apache Tika was unable to parse the document\n");
    writer.append("at " + name + ".\n\n");
    writer.append("The full exception stack trace is included below:\n\n");
    t.printStackTrace(new PrintWriter(writer));

    JEditorPane editor = new JEditorPane("text/plain", writer.toString());
    editor.setEditable(false);//from w  w  w .java 2 s . c  o  m
    editor.setBackground(Color.WHITE);
    editor.setCaretPosition(0);
    editor.setPreferredSize(new Dimension(600, 400));

    JDialog dialog = new JDialog(this, "Apache Tika error");
    dialog.add(new JScrollPane(editor));
    dialog.pack();
    dialog.setVisible(true);
}