Example usage for java.awt Desktop getDesktop

List of usage examples for java.awt Desktop getDesktop

Introduction

In this page you can find the example usage for java.awt Desktop getDesktop.

Prototype

public static synchronized Desktop getDesktop() 

Source Link

Document

Returns the Desktop instance of the current desktop context.

Usage

From source file:by.iharkaratkou.TestServlet.java

public static void openWebpage(URI uri) {
    Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
    if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
        try {/* w  w  w . j  a v a2  s. co  m*/
            desktop.browse(uri);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:uk.codingbadgers.bootstrap.tasks.TaskBootstrapUpdateCheck.java

@Override
public void run(Bootstrap bootstrap) {
    try {/*from  www  .  j a  v  a 2 s  .c  o m*/
        HttpClient client = HttpClients.createDefault();
        HttpGet request = new HttpGet(BootstrapConstants.BOOTSTRAP_UPDATE_URL);
        request.setHeader(new BasicHeader("Accept", BootstrapConstants.GITHUB_MIME_TYPE));

        HttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            JsonArray json = PARSER.parse(new InputStreamReader(entity.getContent())).getAsJsonArray();
            JsonObject release = json.get(0).getAsJsonObject();
            String version = release.get("name").getAsString();

            if (VersionComparator.getInstance().compare(BootstrapConstants.VERSION, version) >= 0) {
                System.out.println("Up to date bootstrap");
            } else {
                Desktop.getDesktop().browse(URI.create(release.get("html_url").getAsString()));
                throw new BootstrapException("Outdated bootstrap.\nPlease update your bootstrap.\n");
            }

            EntityUtils.consume(entity);
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
            System.err.println("Hit rate limit, skipping update check");
        } else {
            System.err.println(
                    "Error sending request to github. Error " + response.getStatusLine().getStatusCode());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:edu.scripps.fl.pubchem.web.session.WebSessionBase.java

protected void debugDocumentToTempFile(Document doc, boolean displayFile) throws IOException {
    File file = File.createTempFile(getClass().getName(), ".html");
    XMLWriter writer = new XMLWriter(new FileOutputStream(file));
    writer.write(doc);/*from w w w .  j a va 2  s. c o m*/
    writer.close();
    if (displayFile)
        Desktop.getDesktop().open(file);
}

From source file:utybo.branchingstorytree.swing.visuals.AboutDialog.java

@SuppressWarnings("unchecked")
public AboutDialog(OpenBSTGUI parent) {
    super(parent);
    setTitle(Lang.get("about.title"));
    setModalityType(ModalityType.APPLICATION_MODAL);

    JPanel banner = new JPanel(new FlowLayout(FlowLayout.CENTER));
    banner.setBackground(OpenBSTGUI.OPENBST_BLUE);
    JLabel lblOpenbst = new JLabel(new ImageIcon(Icons.getImage("FullLogoWhite", 48)));
    lblOpenbst.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    banner.add(lblOpenbst, "flowx,cell 0 0,alignx center");
    getContentPane().add(banner, BorderLayout.NORTH);

    JPanel pan = new JPanel();
    pan.setLayout(new MigLayout("insets 10, gap 10px", "[grow]", "[][][grow]"));
    getContentPane().add(pan, BorderLayout.CENTER);

    JLabel lblWebsite = new JLabel("https://utybo.github.io/BST/");
    Font f = lblWebsite.getFont();
    @SuppressWarnings("rawtypes")
    Map attrs = f.getAttributes();
    attrs.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
    lblWebsite.setFont(f.deriveFont(attrs));
    lblWebsite.setForeground(OpenBSTGUI.OPENBST_BLUE);
    lblWebsite.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    lblWebsite.addMouseListener(new MouseAdapter() {
        @Override//from  w w  w .j a  va2 s .c o m
        public void mouseClicked(MouseEvent e) {
            if (Desktop.isDesktopSupported()) {
                try {
                    Desktop.getDesktop().browse(new URL("https://utybo.github.io/BST/").toURI());
                } catch (IOException | URISyntaxException e1) {
                    OpenBST.LOG.warn("Exception when trying to open website", e1);
                }
            }
        }
    });
    pan.add(lblWebsite, "cell 0 0,alignx center");

    JLabel lblVersion = new JLabel(Lang.get("about.version").replace("$v", OpenBST.VERSION));
    pan.add(lblVersion, "flowy,cell 0 1");

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBorder(new LineBorder(pan.getBackground().darker(), 1, false));
    pan.add(scrollPane, "cell 0 2,grow");

    JTextArea textArea = new JTextArea();
    textArea.setMargin(new Insets(5, 5, 5, 5));
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    textArea.setFont(new Font(textArea.getFont().getFontName(), Font.PLAIN, (int) (Icons.getScale() * 11)));

    try (InputStream in = getClass().getResourceAsStream("/utybo/branchingstorytree/swing/about.txt");) {
        textArea.setText(IOUtils.toString(in, StandardCharsets.UTF_8));
    } catch (IOException ex) {
        OpenBST.LOG.warn("Loading about information failed", ex);
    }
    textArea.setEditable(false);
    textArea.setCaretPosition(0);
    scrollPane.setViewportView(textArea);

    JLabel lblTranslatedBy = new JLabel(Lang.get("author"));
    pan.add(lblTranslatedBy, "cell 0 1");

    setSize((int) (Icons.getScale() * 450), (int) (Icons.getScale() * 400));
    setLocationRelativeTo(parent);
}

From source file:dpfmanager.shell.interfaces.gui.component.show.ShowController.java

public void showSingleReport(String type, String path) {
    //    getContext().send(BasicConfig.MODULE_MESSAGE, new LogMessage(getClass(), Level.DEBUG, "Showing report..."));
    switch (type) {
    case "html":
        getView().showWebView(path);/*from  ww  w .ja v  a2 s.  com*/
        break;
    case "xml":
        showComboTextArea(path, "xml");
        break;
    case "mets":
        showComboTextArea(path, "mets.xml");
        break;
    case "json":
        showComboTextArea(path, "json");
        break;
    case "pdf":
        try {
            getView().getContext().send(GuiConfig.PERSPECTIVE_REPORTS, new UiMessage());
            Desktop.getDesktop().open(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;
    default:
        break;
    }
}

From source file:xtrememp.update.SoftwareUpdate.java

public static void checkForUpdates(final boolean showDialogs) {
    checkForUpdatesWorker = new SwingWorker<Version, Void>() {

        @Override//from www.java  2 s  . co  m
        protected Version doInBackground() throws Exception {
            logger.debug("checkForUpdates: started...");
            long startTime = System.currentTimeMillis();
            Version version = getLastVersion(new URL(updatesURL));
            if (showDialogs) {
                // Simulate (if needed) a delay of 2 sec max to let the user cancel the task.
                long delayTime = System.currentTimeMillis() - startTime - 2000;
                if (delayTime > 0) {
                    Thread.sleep(delayTime);
                }
            }
            return version;
        }

        @Override
        protected void done() {
            logger.debug("checkForUpdates: done");
            if (checkForUpdatesDialog != null && checkForUpdatesDialog.isVisible()) {
                checkForUpdatesDialog.dispose();
            }
            if (!isCancelled()) {
                try {
                    newerVersion = get();
                    if (newerVersion != null && newerVersion.compareTo(currentVersion) == 1) {
                        logger.debug("checkForUpdates: currentVersion = {}", currentVersion);
                        logger.debug("checkForUpdates: newerVersion = {}", newerVersion);
                        logger.debug("SoftwareUpdate::checkForUpdates: updates found");
                        Object[] options = { tr("Button.Cancel") };
                        Desktop desktop = null;
                        if (Desktop.isDesktopSupported()) {
                            desktop = Desktop.getDesktop();
                            if (desktop.isSupported(Desktop.Action.BROWSE)) {
                                options = new Object[] { tr("Button.Download"), tr("Button.Cancel") };
                            }
                        }
                        JPanel panel = new JPanel(new BorderLayout(0, 10));
                        panel.add(new JLabel("<html>" + tr("Dialog.SoftwareUpdate.UpdatesFound") + " ("
                                + newerVersion + ")</html>"), BorderLayout.CENTER);
                        JCheckBox hideCheckBox = null;
                        if (Settings.isAutomaticUpdatesEnabled()) {
                            hideCheckBox = new JCheckBox(
                                    tr("Dialog.SoftwareUpdate.DisableAutomaticCheckForUpdates"));
                            panel.add(hideCheckBox, BorderLayout.SOUTH);
                        }
                        int option = JOptionPane.showOptionDialog(XtremeMP.getInstance().getMainFrame(), panel,
                                tr("Dialog.SoftwareUpdate"), JOptionPane.OK_CANCEL_OPTION,
                                JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                        if (hideCheckBox != null) {
                            Settings.setAutomaticUpdatesEnabled(!hideCheckBox.isSelected());
                        }
                        if ((options.length == 2) && (option == JOptionPane.OK_OPTION)) {
                            try {
                                URL url = new URL(newerVersion.getDownloadURL());
                                desktop.browse(url.toURI());
                            } catch (Exception ex) {
                                logger.error(ex.getMessage(), ex);
                            }
                        }
                    } else {
                        logger.debug("checkForUpdates: no updates found");
                        if (showDialogs) {
                            JOptionPane.showMessageDialog(XtremeMP.getInstance().getMainFrame(),
                                    tr("Dialog.SoftwareUpdate.NoUpdatesFound"), tr("Dialog.SoftwareUpdate"),
                                    JOptionPane.INFORMATION_MESSAGE);
                        }
                    }
                } catch (Exception ex) {
                    logger.error(ex.getMessage(), ex);
                    if (showDialogs) {
                        JOptionPane.showMessageDialog(XtremeMP.getInstance().getMainFrame(),
                                tr("Dialog.SoftwareUpdate.ConnectionFailure"), tr("Dialog.SoftwareUpdate"),
                                JOptionPane.INFORMATION_MESSAGE);
                    }
                }
            }
        }
    };
    checkForUpdatesWorker.execute();
}

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 {/*from www.  j  av a  2 s .  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:DesktopAppTest.java

public DesktopAppFrame() {
    setLayout(new GridBagLayout());
    final JFileChooser chooser = new JFileChooser();
    JButton fileChooserButton = new JButton("...");
    final JTextField fileField = new JTextField(20);
    fileField.setEditable(false);//w ww.  j a  v a2 s  .  co  m
    JButton openButton = new JButton("Open");
    JButton editButton = new JButton("Edit");
    JButton printButton = new JButton("Print");
    final JTextField browseField = new JTextField();
    JButton browseButton = new JButton("Browse");
    final JTextField toField = new JTextField();
    final JTextField subjectField = new JTextField();
    JButton mailButton = new JButton("Mail");

    openButton.setEnabled(false);
    editButton.setEnabled(false);
    printButton.setEnabled(false);
    browseButton.setEnabled(false);
    mailButton.setEnabled(false);

    if (Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.OPEN))
            openButton.setEnabled(true);
        if (desktop.isSupported(Desktop.Action.EDIT))
            editButton.setEnabled(true);
        if (desktop.isSupported(Desktop.Action.PRINT))
            printButton.setEnabled(true);
        if (desktop.isSupported(Desktop.Action.BROWSE))
            browseButton.setEnabled(true);
        if (desktop.isSupported(Desktop.Action.MAIL))
            mailButton.setEnabled(true);
    }

    fileChooserButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (chooser.showOpenDialog(DesktopAppFrame.this) == JFileChooser.APPROVE_OPTION)
                fileField.setText(chooser.getSelectedFile().getAbsolutePath());
        }
    });

    openButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().open(chooser.getSelectedFile());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    editButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().edit(chooser.getSelectedFile());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    printButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().print(chooser.getSelectedFile());
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    browseButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.getDesktop().browse(new URI(browseField.getText()));
            } catch (URISyntaxException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    mailButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                String subject = percentEncode(subjectField.getText());
                URI uri = new URI("mailto:" + toField.getText() + "?subject=" + subject);

                System.out.println(uri);
                Desktop.getDesktop().mail(uri);
            } catch (URISyntaxException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    });

    JPanel buttonPanel = new JPanel();
    ((FlowLayout) buttonPanel.getLayout()).setHgap(2);
    buttonPanel.add(openButton);
    buttonPanel.add(editButton);
    buttonPanel.add(printButton);

    add(fileChooserButton, new GBC(0, 0).setAnchor(GBC.EAST).setInsets(2));
    add(fileField, new GBC(1, 0).setFill(GBC.HORIZONTAL));
    add(buttonPanel, new GBC(2, 0).setAnchor(GBC.WEST).setInsets(0));
    add(browseField, new GBC(1, 1).setFill(GBC.HORIZONTAL));
    add(browseButton, new GBC(2, 1).setAnchor(GBC.WEST).setInsets(2));
    add(new JLabel("To:"), new GBC(0, 2).setAnchor(GBC.EAST).setInsets(5, 2, 5, 2));
    add(toField, new GBC(1, 2).setFill(GBC.HORIZONTAL));
    add(mailButton, new GBC(2, 2).setAnchor(GBC.WEST).setInsets(2));
    add(new JLabel("Subject:"), new GBC(0, 3).setAnchor(GBC.EAST).setInsets(5, 2, 5, 2));
    add(subjectField, new GBC(1, 3).setFill(GBC.HORIZONTAL));

    pack();
}

From source file:org.swiftexplorer.gui.AboutDlg.java

private static void open(URI uri) {
    if (Desktop.isDesktopSupported()) {
        try {//from  w w  w  .  ja  va 2s.  c  o m
            Desktop.getDesktop().browse(uri);
        } catch (IOException e) {

        }
    }
}

From source file:de.mendelson.comm.as2.client.HTMLPanel.java

/**Listen to be a HyperlinkListener*/
@Override/*  w w w .j  a v a  2s  .  c  om*/
public void hyperlinkUpdate(HyperlinkEvent e) {
    if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
        try {
            URI uri = new URI(e.getURL().toExternalForm());
            Desktop.getDesktop().browse(uri);
        } catch (Exception ex) {
            //nop
        }
    }
    if (e.getEventType() == HyperlinkEvent.EventType.ENTERED) {
        jEditorPane.setCursor(new Cursor(Cursor.HAND_CURSOR));
    }
    if (e.getEventType() == HyperlinkEvent.EventType.EXITED) {
        jEditorPane.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    }
}