Example usage for javax.swing JOptionPane createDialog

List of usage examples for javax.swing JOptionPane createDialog

Introduction

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

Prototype

public JDialog createDialog(Component parentComponent, String title) throws HeadlessException 

Source Link

Document

Creates and returns a new JDialog wrapping this centered on the parentComponent in the parentComponent's frame.

Usage

From source file:cz.nn.copytables.gui.CopyTablesGUI.java

private void showDialog(String title, String message) {
    JOptionPane pane = new JOptionPane(message, JOptionPane.INFORMATION_MESSAGE);
    JDialog dialog = pane.createDialog(this, title);
    dialog.setAlwaysOnTop(true);// ww  w .j  a  v a  2s. c o  m
    dialog.setVisible(true);
    logger.info("setVisible");
}

From source file:de.juwimm.cms.http.AuthenticationStreamSupportingHttpInvokerRequestExecutor.java

@Override
protected void executePostMethod(HttpInvokerClientConfiguration config, HttpClient httpClient,
        PostMethod postMethod) throws IOException {
    HttpClientWrapper.getInstance().setHostConfiguration(super.getHttpClient(),
            new URL(config.getServiceUrl()));
    try {//w  ww .ja v  a 2  s. c o m
        super.executePostMethod(config, httpClient, postMethod);
        //if call succeeds 
        isErrorMessageShown = false;
    } catch (IOException e) {
        if ((e instanceof SocketException && e.getMessage().equals("Connection reset"))
                || (e instanceof ConnectException && e.getMessage().equals("Connection refused"))) {
            if (!isErrorMessageShown) {
                isErrorMessageShown = true;
                JOptionPane errorOptionPane = new JOptionPane(
                        Constants.rb.getString("exception.connectionToServerLost"),
                        JOptionPane.INFORMATION_MESSAGE);
                JDialog errorDialogPane = errorOptionPane.createDialog(UIConstants.getMainFrame(),
                        rb.getString("dialog.title"));
                errorDialogPane.setModalityType(ModalityType.MODELESS);
                errorDialogPane.setVisible(true);
                errorDialogPane.setEnabled(true);
                errorDialogPane.addWindowListener(new WindowAdapter() {
                    public void windowDeactivated(WindowEvent e) {
                        if (((JDialog) e.getSource()).isVisible() == false) {
                            isErrorMessageShown = false;
                        }
                    }
                });

            }
            log.error("server is not reachable");
        } else {
            e.printStackTrace();
        }
    }
    System.out.println(postMethod.getResponseHeaders());
}

From source file:edu.scripps.fl.pubchem.xmltool.gui.GUIComponent.java

public void openPDF(boolean isInternalR, File pdf, Component comp) throws FileNotFoundException {
    if (isInternalR) {
        try {/* w  ww.  ja v  a 2s.  c  o m*/
            Desktop.getDesktop().open(pdf);
        } catch (Exception ex) {
            log.info(ex.getMessage());
            String msg = "Unable to open PDF format through java. Would you like to save "
                    + pdf.getAbsoluteFile() + " in a new location?";
            JOptionPane pane = new JOptionPane(msg, JOptionPane.QUESTION_MESSAGE,
                    JOptionPane.YES_NO_CANCEL_OPTION, null, null, JOptionPane.YES_OPTION);
            JDialog dialog = pane.createDialog(comp, "Report PDF");
            dialog.setVisible(true);
            Object choice = pane.getValue();
            if (choice.equals(JOptionPane.YES_OPTION)) {
                jfcFiles = new JFileChooser();
                jfcFiles.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                int state = jfcFiles.showSaveDialog(comp);

                if (state == JFileChooser.APPROVE_OPTION) {
                    File file = checkFileExtension(".pdf");
                    log.info("Opening: " + file.getName() + ".");
                    if (file != null)
                        pdf.renameTo(file);
                } else {
                    log.info("Open command cancelled by user.");
                }
            }
        }
    }
}

From source file:JuliaSet3.java

public void printToService(PrintService service, PrintRequestAttributeSet printAttributes) {
    // Wrap ourselves in the PrintableComponent class defined by JuliaSet2.
    String title = "Julia set for c={" + cx + "," + cy + "}";
    Printable printable = new PrintableComponent(this, title);

    // Now create a Doc that encapsulate the Printable object and its type
    DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
    Doc doc = new SimpleDoc(printable, flavor, null);

    // Java 1.1 uses PrintJob.
    // Java 1.2 uses PrinterJob.
    // Java 1.4 uses DocPrintJob. Create one from the service
    DocPrintJob job = service.createPrintJob();

    // Set up a dialog box to monitor printing status
    final JOptionPane pane = new JOptionPane("Printing...", JOptionPane.PLAIN_MESSAGE);
    JDialog dialog = pane.createDialog(this, "Print Status");
    // This listener object updates the dialog as the status changes
    job.addPrintJobListener(new PrintJobAdapter() {
        public void printJobCompleted(PrintJobEvent e) {
            pane.setMessage("Printing complete.");
        }/*w w w.  j ava  2  s.c om*/

        public void printDataTransferCompleted(PrintJobEvent e) {
            pane.setMessage("Document transfered to printer.");
        }

        public void printJobRequiresAttention(PrintJobEvent e) {
            pane.setMessage("Check printer: out of paper?");
        }

        public void printJobFailed(PrintJobEvent e) {
            pane.setMessage("Print job failed");
        }
    });

    // Show the dialog, non-modal.
    dialog.setModal(false);
    dialog.show();

    // Now print the Doc to the DocPrintJob
    try {
        job.print(doc, printAttributes);
    } catch (PrintException e) {
        // Display any errors to the dialog box
        pane.setMessage(e.toString());
    }
}

From source file:esmska.gui.AboutFrame.java

private void licenseButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_licenseButtonActionPerformed
    //show licence
    try {/*from   w ww .j ava  2s.  co m*/
        logger.fine("Showing license...");
        String license = IOUtils.toString(getClass().getResourceAsStream(RES + "license.txt"), "UTF-8");
        final String agpl = IOUtils.toString(getClass().getResourceAsStream(RES + "gnu-agpl.txt"), "UTF-8");
        license = MiscUtils.escapeHtml(license);
        license = license.replaceAll("GNU Affero General Public License",
                "<a href=\"agpl\">GNU Affero General Public License</a>");

        final JTextPane tp = new JTextPane();
        tp.setContentType("text/html; charset=UTF-8");
        tp.setText("<html><pre>" + license + "</pre></html>");
        tp.setEditable(false);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        tp.setPreferredSize(new Dimension((int) d.getWidth() / 2, (int) d.getHeight() / 2)); //reasonable size
        tp.setCaretPosition(0);
        //make links clickable
        tp.addHyperlinkListener(new HyperlinkListener() {
            @Override
            public void hyperlinkUpdate(final HyperlinkEvent e) {
                if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                    logger.fine("Showing GNU AGPL...");
                    tp.setText(null);
                    tp.setContentType("text/plain");
                    tp.setText(agpl);
                    tp.setCaretPosition(0);
                }
            }
        });

        String option = l10n.getString("AboutFrame.Acknowledge");
        JOptionPane op = new JOptionPane(new JScrollPane(tp), JOptionPane.INFORMATION_MESSAGE,
                JOptionPane.DEFAULT_OPTION, null, new Object[] { option }, option);
        JDialog dialog = op.createDialog(this, l10n.getString("AboutFrame.License"));
        dialog.setResizable(true);
        dialog.pack();
        dialog.setVisible(true);
    } catch (IOException ex) {
        logger.log(Level.WARNING, "Could not show license", ex);
    }
}

From source file:esmska.gui.AboutFrame.java

private void creditsButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_creditsButtonActionPerformed
    //show credits
    try {/*  w  ww. ja  v  a  2s. co m*/
        logger.fine("Showing credits...");
        String credits = IOUtils.toString(getClass().getResourceAsStream(RES + "credits.html"), "UTF-8");
        String translators = l10n.getString("Translators");
        if ("translator-credits".equals(translators)) {
            //there are no translators mentioned
            translators = "";
        } else {
            translators = translators.replaceAll("\n", "<br>\n").replaceAll("\n  ", "\n&nbsp;&nbsp;");
            //add hyperlinks to the Launchpad URLs
            translators = translators.replaceAll("(https://[^<]*)", "<a href=\"$1\">$1</a>");
        }

        String document = MessageFormat.format(credits, l10n.getString("Credits.authors"),
                l10n.getString("Credits.contributors"), l10n.getString("Credits.graphics"),
                l10n.getString("Credits.sponsors"), l10n.getString("Credits.translators"), translators,
                Links.DONATORS, l10n.getString("Credits.moreDonators"),
                MessageFormat.format(l10n.getString("Credits.packagers"), Links.DOWNLOAD));

        JTextPane tp = new JTextPane();
        tp.setContentType("text/html; charset=UTF-8");
        tp.setText(document);
        tp.setEditable(false);
        tp.setPreferredSize(new Dimension(450, 400));
        tp.setCaretPosition(0);
        //make links clickable
        tp.addHyperlinkListener(new HyperlinkListener() {
            @Override
            public void hyperlinkUpdate(final HyperlinkEvent e) {
                if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED && Desktop.isDesktopSupported()) {
                    try {
                        logger.fine("Browsing URL: " + e.getURL());
                        Desktop.getDesktop().browse(e.getURL().toURI());
                    } catch (Exception ex) {
                        logger.log(Level.SEVERE, "Can't browse hyperlink: " + e.getURL(), ex);
                    }
                }
            }
        });

        String option = l10n.getString("AboutFrame.Thank_you");
        JOptionPane op = new JOptionPane(new JScrollPane(tp), JOptionPane.INFORMATION_MESSAGE,
                JOptionPane.DEFAULT_OPTION, null, new Object[] { option }, option);
        JDialog dialog = op.createDialog(this, l10n.getString("AboutFrame.Credits"));
        dialog.setResizable(true);
        dialog.pack();
        dialog.setVisible(true);
    } catch (IOException e) {
        logger.log(Level.WARNING, "Could not show credits", e);
    }
}

From source file:Installer.java

public static JLabel linkify(final String text, String URL, String toolTip) {
    URI temp = null;/* w  w  w  .  ja  va2  s .c om*/
    try {
        temp = new URI(URL);
    } catch (Exception e) {
        e.printStackTrace();
    }
    final URI uri = temp;
    final JLabel link = new JLabel();
    link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>");
    if (!toolTip.equals(""))
        link.setToolTipText(toolTip);
    link.setCursor(new Cursor(Cursor.HAND_CURSOR));
    link.addMouseListener(new MouseListener() {
        public void mouseExited(MouseEvent arg0) {
            link.setText("<HTML><FONT color=\"#000099\">" + text + "</FONT></HTML>");
        }

        public void mouseEntered(MouseEvent arg0) {
            link.setText("<HTML><FONT color=\"#000099\"><U>" + text + "</U></FONT></HTML>");
        }

        public void mouseClicked(MouseEvent arg0) {
            if (Desktop.isDesktopSupported()) {
                try {
                    Desktop.getDesktop().browse(uri);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                JOptionPane pane = new JOptionPane("Could not open link.");
                JDialog dialog = pane.createDialog(new JFrame(), "");
                dialog.setVisible(true);
            }
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
        }
    });
    return link;
}

From source file:com.ga.forms.DailyLogAddUI.java

private void checkInOutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkInOutButtonActionPerformed
    DailyLogRecord log = new DailyLogRecord();
    if (DailyLogAddUI.checkIn && !DailyLogAddUI.breakDone) {
        args = new HashMap();
        DailyLogAddUI.breakDone = true;//w w  w .  ja  v  a2s  .c  o  m
        args.put("checked-in", Boolean.toString(DailyLogAddUI.checkIn));
        args.put("had-break", Boolean.toString(DailyLogAddUI.breakDone));
        args.put("checked-out", Boolean.toString(DailyLogAddUI.checkOut));
        if (yesRdButton.isSelected() == true) {
            this.timeOnBreak = "00:30";
        } else if (customRdButton.isSelected() == true) {
            this.timeOnBreak = customBreakTimeTextField.getText();
        } else {
            this.timeOnBreak = "00:00";
        }
        log.setDailyLogRecord(dateDisplayLbl.getText(), dayDisplayLbl.getText(),
                checkInTimeCombo.getSelectedItem().toString(), "", this.timeOnBreak, "", "", "", args);
        doc = (DBObject) JSON.parse(log.getDailyLogRecord().toString());
        args.clear();
        args.put("date", dateDisplayLbl.getText());
        log.updateRecord(doc, args);
    } else if (DailyLogAddUI.checkIn && DailyLogAddUI.breakDone && !DailyLogAddUI.checkOut) {
        args = new HashMap();
        DailyLogAddUI.checkOut = true;
        args.put("checked-in", Boolean.toString(DailyLogAddUI.checkIn));
        args.put("had-break", Boolean.toString(DailyLogAddUI.breakDone));
        args.put("checked-out", Boolean.toString(DailyLogAddUI.checkOut));
        DailyLogDuration durationAgent = new DailyLogDuration();
        durationAgent.calculateCurrentDuration(checkInTimeCombo.getSelectedItem().toString(), this.timeOnBreak,
                checkOutTimeCombo.getSelectedItem().toString());
        this.duration = durationAgent.getCurrentDuration();

        JFrame parent = new JFrame();
        JOptionPane optionPane = new JOptionPane("Duration: " + this.duration + "\n\nDo you want to Check Out?",
                JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
        JDialog msgDialog = optionPane.createDialog(parent, "DLM");
        msgDialog.setVisible(true);

        if (optionPane.getValue().equals(0)) {
            int hours = Integer.parseInt(this.duration.split(":")[0]);
            int minutes = Integer.parseInt(this.duration.split(":")[1]);
            if (hours < 9) {
                durationAgent.calculateUnderTime(this.duration);
                this.underTime = durationAgent.getUnderTime();
                this.overTime = "00:00";
            } else if (hours >= 9 && minutes > 0 && minutes < 60) {
                this.underTime = "00:00";
                durationAgent.calculateOverTime(this.duration);
                this.overTime = durationAgent.getOverTime();

            } else {
                this.underTime = "00:00";
                this.overTime = "00:00";
            }
            log.setDailyLogRecord(dateDisplayLbl.getText(), dayDisplayLbl.getText(),
                    checkInTimeCombo.getSelectedItem().toString(),
                    checkOutTimeCombo.getSelectedItem().toString(), this.timeOnBreak, this.duration,
                    this.underTime, this.overTime, args);
            doc = (DBObject) JSON.parse(log.getDailyLogRecord().toString());
            args.clear();
            args.put("date", dateDisplayLbl.getText());
            log.updateRecord(doc, args);
        } else {
            msgDialog.dispose();
        }
    } else {
        args = new HashMap();
        DailyLogAddUI.checkIn = true;
        args.put("checked-in", Boolean.toString(DailyLogAddUI.checkIn));
        args.put("had-break", Boolean.toString(DailyLogAddUI.breakDone));
        args.put("checked-out", Boolean.toString(DailyLogAddUI.checkOut));
        log.setDailyLogRecord(dateDisplayLbl.getText(), dayDisplayLbl.getText(),
                checkInTimeCombo.getSelectedItem().toString(), "", "", "", "", "", args);
        doc = (DBObject) JSON.parse(log.getDailyLogRecord().toString());
        log.insertRecord(doc);

    }

}

From source file:captureplugin.CapturePlugin.java

/**
 * Check the programs after data update.
 *///  www . jav a  2s .c o  m
public void handleTvDataUpdateFinished() {
    mNeedsUpdate = true;

    if (mAllowedToShowDialog) {
        mNeedsUpdate = false;

        DeviceIf[] devices = mConfig.getDeviceArray();

        final DefaultTableModel model = new DefaultTableModel() {
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        model.setColumnCount(5);
        model.setColumnIdentifiers(new String[] { mLocalizer.msg("device", "Device"),
                Localizer.getLocalization(Localizer.I18N_CHANNEL), mLocalizer.msg("date", "Date"),
                ProgramFieldType.START_TIME_TYPE.getLocalizedName(),
                ProgramFieldType.TITLE_TYPE.getLocalizedName() });

        JTable table = new JTable(model);
        table.getTableHeader().setReorderingAllowed(false);
        table.getTableHeader().setResizingAllowed(false);
        table.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer() {
            public Component getTableCellRendererComponent(JTable renderTable, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) {
                Component c = super.getTableCellRendererComponent(renderTable, value, isSelected, hasFocus, row,
                        column);

                if (value instanceof DeviceIf) {
                    if (((DeviceIf) value).getDeleteRemovedProgramsAutomatically() && !isSelected) {
                        c.setForeground(Color.red);
                    }
                }

                return c;
            }
        });

        int[] columnWidth = new int[5];

        for (int i = 0; i < columnWidth.length; i++) {
            columnWidth[i] = UiUtilities.getStringWidth(table.getFont(), model.getColumnName(i)) + 10;
        }

        for (DeviceIf device : devices) {
            Program[] deleted = device.checkProgramsAfterDataUpdateAndGetDeleted();

            if (deleted != null && deleted.length > 0) {
                for (Program p : deleted) {
                    if (device.getDeleteRemovedProgramsAutomatically() && !p.isExpired() && !p.isOnAir()) {
                        device.remove(UiUtilities.getLastModalChildOf(getParentFrame()), p);
                    } else {
                        device.removeProgramWithoutExecution(p);
                    }

                    if (!p.isExpired()) {
                        Object[] o = new Object[] { device, p.getChannel().getName(), p.getDateString(),
                                p.getTimeString(), p.getTitle() };

                        for (int i = 0; i < columnWidth.length; i++) {
                            columnWidth[i] = Math.max(columnWidth[i],
                                    UiUtilities.getStringWidth(table.getFont(), o[i].toString()) + 10);
                        }

                        model.addRow(o);
                    }
                }
            }

            device.getProgramList();
        }

        if (model.getRowCount() > 0) {
            int sum = 0;

            for (int i = 0; i < columnWidth.length; i++) {
                table.getColumnModel().getColumn(i).setPreferredWidth(columnWidth[i]);

                if (i < columnWidth.length - 1) {
                    table.getColumnModel().getColumn(i).setMaxWidth(columnWidth[i]);
                }

                sum += columnWidth[i];
            }

            JScrollPane scrollPane = new JScrollPane(table);
            scrollPane.setPreferredSize(new Dimension(450, 250));

            if (sum > 500) {
                table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                scrollPane.getViewport().setPreferredSize(
                        new Dimension(sum, scrollPane.getViewport().getPreferredSize().height));
            }

            JButton export = new JButton(mLocalizer.msg("exportList", "Export list"));
            export.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JFileChooser chooser = new JFileChooser();
                    chooser.setDialogType(JFileChooser.SAVE_DIALOG);
                    chooser.setFileFilter(new FileFilter() {
                        public boolean accept(File f) {
                            return f.isDirectory() || f.toString().toLowerCase().endsWith(".txt");
                        }

                        public String getDescription() {
                            return "*.txt";
                        }
                    });

                    chooser.setSelectedFile(new File("RemovedPrograms.txt"));
                    if (chooser.showSaveDialog(
                            UiUtilities.getLastModalChildOf(getParentFrame())) == JFileChooser.APPROVE_OPTION) {
                        if (chooser.getSelectedFile() != null) {
                            String file = chooser.getSelectedFile().getAbsolutePath();

                            if (!file.toLowerCase().endsWith(".txt") && file.indexOf('.') == -1) {
                                file = file + ".txt";
                            }

                            if (file.indexOf('.') != -1) {
                                try {
                                    RandomAccessFile write = new RandomAccessFile(file, "rw");
                                    write.setLength(0);

                                    String eolStyle = File.separator.equals("/") ? "\n" : "\r\n";

                                    for (int i = 0; i < model.getRowCount(); i++) {
                                        StringBuilder line = new StringBuilder();

                                        for (int j = 0; j < model.getColumnCount(); j++) {
                                            line.append(model.getValueAt(i, j)).append(' ');
                                        }

                                        line.append(eolStyle);

                                        write.writeBytes(line.toString());
                                    }

                                    write.close();
                                } catch (Exception ee) {
                                }
                            }
                        }
                    }
                }
            });

            Object[] message = {
                    mLocalizer.msg("deletedText",
                            "The data was changed and the following programs were deleted:"),
                    scrollPane, export };

            JOptionPane pane = new JOptionPane();
            pane.setMessage(message);
            pane.setMessageType(JOptionPane.PLAIN_MESSAGE);

            final JDialog d = pane.createDialog(UiUtilities.getLastModalChildOf(getParentFrame()),
                    mLocalizer.msg("CapturePlugin", "CapturePlugin") + " - "
                            + mLocalizer.msg("deletedTitle", "Deleted programs"));
            d.setResizable(true);
            d.setModal(false);

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    d.setVisible(true);
                }
            });
        }
    }
}

From source file:net.sf.nmedit.nomad.core.Nomad.java

public void export() {
    Document doc = getDocumentManager().getSelection();
    if (!(doc instanceof Transferable))
        return;/*from  w  ww .  j  a va 2  s  . c o m*/

    Transferable transferable = (Transferable) doc;

    String title = doc.getTitle();
    if (title == null)
        title = "Export";
    else
        title = "Export '" + title + "'";

    JComboBox src = new JComboBox(transferable.getTransferDataFlavors());
    src.setRenderer(new DefaultListCellRenderer() {
        /**
         * 
         */
        private static final long serialVersionUID = -4553255745845039428L;

        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            String text;
            if (value instanceof DataFlavor) {
                DataFlavor flavor = (DataFlavor) value;
                String mimeType = flavor.getMimeType();
                String humanRep = flavor.getHumanPresentableName();
                String charset = flavor.getParameter("charset");

                if (mimeType == null)
                    text = "?";
                else {
                    text = mimeType;
                    int ix = text.indexOf(';');
                    if (ix >= 0)
                        text = text.substring(0, ix).trim();
                }
                if (charset != null)
                    text += "; charset=" + charset;
                if (humanRep != null)
                    text += " (" + humanRep + ")";
            } else {
                text = String.valueOf(value);
            }
            return super.getListCellRendererComponent(list, text, index, isSelected, cellHasFocus);
        }
    });

    JComboBox dst = new JComboBox(new Object[] { "File", "Clipboard" });

    Object[] msg = { "Source:", doc.getTitle(), "Export as:", src, "Export to:", dst };
    Object[] options = { "Ok", "Cancel" };

    JOptionPane op = new JOptionPane(msg, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null,
            options);

    JDialog dialog = op.createDialog(getWindow(), title);
    dialog.setModal(true);
    dialog.setVisible(true);

    boolean ok = "Ok".equals(op.getValue());

    DataFlavor flavor = (DataFlavor) src.getSelectedItem();
    dialog.dispose();
    if (!ok)
        return;

    if (flavor == null)
        return;

    if ("Clipboard".equals(dst.getSelectedItem())) {
        Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
        cb.setContents(new SelectedTransfer(flavor, transferable), null);
    } else {
        export(transferable, flavor);
    }
}