Example usage for java.awt Desktop isDesktopSupported

List of usage examples for java.awt Desktop isDesktopSupported

Introduction

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

Prototype

public static boolean isDesktopSupported() 

Source Link

Document

Tests whether this class is supported on the current platform.

Usage

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 w w .j  a v  a  2s  .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 ww .j  a  v a2 s .c  o  m*/
            Desktop.getDesktop().browse(uri);
        } catch (IOException e) {

        }
    }
}

From source file:com.photon.phresco.framework.actions.FrameworkBaseAction.java

public void openFolder() {
    if (debugEnabled) {
        S_LOGGER.debug("Entered FrameworkBaseAction.openFolder()");
    }/*from  w ww.  j a  va2  s . co  m*/
    try {
        if (Desktop.isDesktopSupported()) {
            File dir = new File(Utility.getProjectHome() + path);
            if (dir.exists()) {
                Desktop.getDesktop().open(new File(Utility.getProjectHome() + path));
            } else {
                Desktop.getDesktop().open(new File(Utility.getProjectHome()));
            }
        }
    } catch (Exception e) {
        if (debugEnabled) {
            S_LOGGER.error("Unable to open the Path, " + FrameworkUtil.getStackTraceAsString(e));
            new LogErrorReport(e, "Open Folder");
        }
    }
}

From source file:wo.trade.Util.java

public static void openUrlViaBrowser(String url) {
    String s = url;/*  w w w  . j a va  2  s .  co  m*/
    if (Desktop.isDesktopSupported()) {
        try {
            Desktop.getDesktop().browse(new URI(s));
        } catch (Exception e) {
            log.error("Error on opening browser, address: " + s + ": " + e.getMessage(), e);
        }
    } else {
        log.error(("Launch browser failed, please manually visit: " + s));
    }
}

From source file:uk.ac.ucl.cs.cmic.giftcloud.uploadapp.GiftCloudDialogs.java

public void showMessage(final String message) throws HeadlessException {

    final JPanel messagePanel = new JPanel(new GridBagLayout());
    final JEditorPane textField = new JEditorPane();
    textField.setContentType("text/html");
    textField.setText(message);/*from  w  w w.ja  va  2 s.  c o m*/
    textField.setEditable(false);
    textField.setBackground(null);
    textField.setBorder(null);
    textField.setEditable(false);
    textField.setForeground(UIManager.getColor("Label.foreground"));
    textField.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, true);
    textField.setFont(UIManager.getFont("Label.font"));
    textField.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent e) {
            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                if (Desktop.isDesktopSupported()) {
                    try {
                        Desktop.getDesktop().browse(e.getURL().toURI());
                    } catch (IOException e1) {
                        // Ignore failure to launch URL
                    } catch (URISyntaxException e1) {
                        // Ignore failure to launch URL
                    }
                }
            }
        }
    });

    messagePanel.add(textField);
    textField.setAlignmentX(SwingConstants.CENTER);

    JOptionPane.showMessageDialog(mainFrame.getContainer(), messagePanel, applicationName,
            JOptionPane.INFORMATION_MESSAGE, icon);
}

From source file:gmailclientfx.core.GmailClient.java

public static void authorizeUser() throws IOException {

    FLOW = new GoogleAuthorizationCodeFlow.Builder(TRANSPORT, JSON_FACTORY, CLIENT_ID, CLIENT_SECRET, SCOPES)
            //.setApprovalPrompt("select_account")
            .setAccessType("offline").build();

    String url = FLOW.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
    String txtURI = url + "&prompt=select_account";
    String code = "";

    if (Desktop.isDesktopSupported()) {
        try {//from w w w. jav a 2 s  .  c  o m
            Desktop.getDesktop().browse(new URI(txtURI));

            TextInputDialog dialog = new TextInputDialog();
            dialog.setTitle("Verifikacija");
            dialog.setHeaderText(null);
            dialog.setContentText("Unesite verifikacijski kod: ");

            Optional<String> result = dialog.showAndWait();
            if (result.isPresent()) {
                code = result.get();
            }
        } catch (URISyntaxException ex) {
            Logger.getLogger(GmailClient.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Greska prilikom logiranja!");
        }
    }

    GoogleTokenResponse tokenResponse = FLOW.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
    CREDENTIAL = new GoogleCredential.Builder().setTransport(TRANSPORT).setJsonFactory(JSON_FACTORY)
            .setClientSecrets(CLIENT_ID, CLIENT_SECRET).addRefreshListener(new CredentialRefreshListener() {
                @Override
                public void onTokenResponse(Credential credential, TokenResponse tokenResponse) {
                    // Handle success.
                }

                @Override
                public void onTokenErrorResponse(Credential credential, TokenErrorResponse tokenErrorResponse) {
                    // Handle error.
                }
            }).build();

    CREDENTIAL.setFromTokenResponse(tokenResponse);
    GMAIL = new Gmail.Builder(TRANSPORT, JSON_FACTORY, CREDENTIAL).setApplicationName("JavaGmailSend").build();
    PROFILE = GMAIL.users().getProfile("me").execute();
    EMAIL = PROFILE.getEmailAddress();
    USER_ID = PROFILE.getHistoryId();
    ACCESS_TOKEN = CREDENTIAL.getAccessToken();
    REFRESH_TOKEN = CREDENTIAL.getRefreshToken();
    /*Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setTitle("Verifikacija");
    alert.setHeaderText(null);
    alert.setContentText("Uspjena verifikacija!");
    alert.showAndWait();*/
}

From source file:misc.DesktopDemo.java

/**
 * Creates new form DesktopDemo//from   w w w  .  ja  v a 2 s.  com
 */
public DesktopDemo() {
    // init all gui components
    initComponents();
    // disable buttons that launch browser, email client,
    // disable buttons that open, edit, print files
    disableActions();
    // before any Desktop APIs are used, first check whether the API is
    // supported by this particular VM on this particular host
    if (Desktop.isDesktopSupported()) {
        desktop = Desktop.getDesktop();
        // now enable buttons for actions that are supported.
        enableSupportedActions();
    }
    loadFrameIcon();
    setResizable(false);
}

From source file:com.github.aptd.simulation.ui.CHTTPServer.java

/**
 * execute the server instance/*from  w  w w . j  a  v  a  2  s  . c  om*/
 */
public static void execute() {
    if (INSTANCE == null)
        return;

    try {
        INSTANCE.m_server.start();

        // open browser if possible
        if ((CConfiguration.INSTANCE.<Boolean>getOrDefault(true, "openbrowser"))
                && (Desktop.isDesktopSupported()))
            Desktop.getDesktop()
                    .browse(new URI("http://"
                            + CConfiguration.INSTANCE.<String>getOrDefault("localhost", "httpserver", "host")
                            + ":" + CConfiguration.INSTANCE.<Integer>getOrDefault(8000, "httpserver", "port")));

        INSTANCE.m_server.join();
    } catch (final InterruptedException | URISyntaxException | IOException l_exception) {
        throw new CSemanticException(l_exception);
    } catch (final Exception l_exception) {
        throw new CRuntimeException(l_exception);
    } finally {
        INSTANCE.m_server.destroy();
    }
}

From source file:org.lightjason.trafficsimulation.ui.CHTTPServer.java

/**
 * execute the server instance/*from  w  w  w  .jav  a  2s  .  co m*/
 */
public static void execute() {
    if (INSTANCE == null)
        return;

    try {
        INSTANCE.m_server.start();

        // open browser if possible
        if ((CConfiguration.INSTANCE.<Boolean>getOrDefault(true, "openbrowser"))
                && (Desktop.isDesktopSupported()))
            Desktop.getDesktop()
                    .browse(new URI("http://"
                            + CConfiguration.INSTANCE.<String>getOrDefault("localhost", "httpserver", "host")
                            + ":" + CConfiguration.INSTANCE.<Integer>getOrDefault(8000, "httpserver", "port")));

        INSTANCE.m_server.join();

    } catch (final Exception l_exception) {
        throw new RuntimeException(l_exception);
    } finally {
        INSTANCE.m_server.destroy();
    }
}

From source file:com.edduarte.protbox.ui.windows.RestoreFileWindow.java

private RestoreFileWindow(final PReg registry) {
    super();/*from  w ww . j a  v  a  2s  . co  m*/
    setLayout(null);

    final JTextField searchField = new JTextField();
    searchField.setLayout(null);
    searchField.setBounds(2, 2, 301, 26);
    searchField.setBorder(new LineBorder(Color.lightGray));
    searchField.setFont(Constants.FONT);
    add(searchField);

    final JLabel noBackupFilesLabel = new JLabel("<html>No backups files were found!<br><br>"
            + "<font color=\"gray\">If you think there is a problem with the<br>"
            + "backup system, please create an issue here:<br>"
            + "<a href=\"#\">https://github.com/com.edduarte/protbox/issues</a></font></html>");
    noBackupFilesLabel.setLayout(null);
    noBackupFilesLabel.setBounds(20, 50, 300, 300);
    noBackupFilesLabel.setFont(Constants.FONT.deriveFont(14f));
    noBackupFilesLabel.addMouseListener((OnMouseClick) e -> {
        String urlPath = "https://github.com/com.edduarte/protbox/issues";

        try {

            if (Desktop.isDesktopSupported()) {
                Desktop.getDesktop().browse(new URI(urlPath));

            } else {
                if (SystemUtils.IS_OS_WINDOWS) {
                    Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + urlPath);

                } else {
                    java.util.List<String> browsers = Lists.newArrayList("firefox", "opera", "safari",
                            "mozilla", "chrome");

                    for (String browser : browsers) {
                        if (Runtime.getRuntime().exec(new String[] { "which", browser }).waitFor() == 0) {

                            Runtime.getRuntime().exec(new String[] { browser, urlPath });
                            break;
                        }
                    }
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    });

    DefaultMutableTreeNode rootTreeNode = registry.buildEntryTree();
    final JTree tree = new JTree(rootTreeNode);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    if (rootTreeNode.getChildCount() == 0) {
        searchField.setEnabled(false);
        add(noBackupFilesLabel);
    }
    expandTree(tree);
    tree.setLayout(null);
    tree.setRootVisible(false);
    tree.setEditable(false);
    tree.setCellRenderer(new SearchableTreeCellRenderer(searchField));
    searchField.addKeyListener((OnKeyReleased) e -> {

        // update and expand tree
        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
        model.nodeStructureChanged((TreeNode) model.getRoot());
        expandTree(tree);
    });
    final JScrollPane scroll = new JScrollPane(tree, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scroll.setBorder(new DropShadowBorder());
    scroll.setBorder(new LineBorder(Color.lightGray));
    scroll.setBounds(2, 30, 334, 360);
    add(scroll);

    JLabel close = new JLabel(new ImageIcon(Constants.getAsset("close.png")));
    close.setLayout(null);
    close.setBounds(312, 7, 18, 18);
    close.setFont(Constants.FONT);
    close.setForeground(Color.gray);
    close.addMouseListener((OnMouseClick) e -> dispose());
    add(close);

    final JLabel permanentDeleteButton = new JLabel(new ImageIcon(Constants.getAsset("permanent.png")));
    permanentDeleteButton.setLayout(null);
    permanentDeleteButton.setBounds(91, 390, 40, 39);
    permanentDeleteButton.setBackground(Color.black);
    permanentDeleteButton.setEnabled(false);
    permanentDeleteButton.addMouseListener((OnMouseClick) e -> {
        if (permanentDeleteButton.isEnabled()) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            PbxEntry entry = (PbxEntry) node.getUserObject();

            if (JOptionPane.showConfirmDialog(null,
                    "Are you sure you wish to permanently delete '" + entry.realName()
                            + "'?\nThis file and its "
                            + "backup copies will be deleted immediately. You cannot undo this action.",
                    "Confirm Cancel", JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE) == JOptionPane.YES_OPTION) {

                registry.permanentDelete(entry);
                dispose();
                RestoreFileWindow.getInstance(registry);

            } else {
                setVisible(true);
            }
        }
    });
    add(permanentDeleteButton);

    final JLabel configBackupsButton = new JLabel(new ImageIcon(Constants.getAsset("config.png")));
    configBackupsButton.setLayout(null);
    configBackupsButton.setBounds(134, 390, 40, 39);
    configBackupsButton.setBackground(Color.black);
    configBackupsButton.setEnabled(false);
    configBackupsButton.addMouseListener((OnMouseClick) e -> {
        if (configBackupsButton.isEnabled()) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            PbxEntry entry = (PbxEntry) node.getUserObject();
            if (entry instanceof PbxFile) {
                PbxFile pbxFile = (PbxFile) entry;

                JFrame frame = new JFrame("Choose backup policy");
                Object option = JOptionPane.showInputDialog(frame,
                        "Choose below the backup policy for this file:", "Choose backup",
                        JOptionPane.QUESTION_MESSAGE, null, PbxFile.BackupPolicy.values(),
                        pbxFile.getBackupPolicy());

                if (option == null) {
                    setVisible(true);
                    return;
                }
                PbxFile.BackupPolicy pickedPolicy = PbxFile.BackupPolicy.valueOf(option.toString());
                pbxFile.setBackupPolicy(pickedPolicy);
            }
            setVisible(true);
        }
    });
    add(configBackupsButton);

    final JLabel restoreBackupButton = new JLabel(new ImageIcon(Constants.getAsset("restore.png")));
    restoreBackupButton.setLayout(null);
    restoreBackupButton.setBounds(3, 390, 85, 39);
    restoreBackupButton.setBackground(Color.black);
    restoreBackupButton.setEnabled(false);
    restoreBackupButton.addMouseListener((OnMouseClick) e -> {
        if (restoreBackupButton.isEnabled()) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            PbxEntry entry = (PbxEntry) node.getUserObject();
            if (entry instanceof PbxFolder) {
                registry.restoreFolderFromEntry((PbxFolder) entry);

            } else if (entry instanceof PbxFile) {
                PbxFile pbxFile = (PbxFile) entry;
                java.util.List<String> snapshots = pbxFile.snapshotsToString();
                if (snapshots.isEmpty()) {
                    setVisible(true);
                    return;
                }

                JFrame frame = new JFrame("Choose backup");
                Object option = JOptionPane.showInputDialog(frame,
                        "Choose below what backup snapshot would you like restore:", "Choose backup",
                        JOptionPane.QUESTION_MESSAGE, null, snapshots.toArray(), snapshots.get(0));

                if (option == null) {
                    setVisible(true);
                    return;
                }
                int pickedIndex = snapshots.indexOf(option.toString());
                registry.restoreFileFromEntry((PbxFile) entry, pickedIndex);
            }
            dispose();
        }
    });
    add(restoreBackupButton);

    tree.addMouseListener((OnMouseClick) e -> {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
        if (node != null) {
            PbxEntry entry = (PbxEntry) node.getUserObject();
            if ((entry instanceof PbxFolder && entry.areNativeFilesDeleted())) {
                permanentDeleteButton.setEnabled(true);
                restoreBackupButton.setEnabled(true);
                configBackupsButton.setEnabled(false);

            } else if (entry instanceof PbxFile) {
                permanentDeleteButton.setEnabled(true);
                restoreBackupButton.setEnabled(true);
                configBackupsButton.setEnabled(true);

            } else {
                permanentDeleteButton.setEnabled(false);
                restoreBackupButton.setEnabled(false);
                configBackupsButton.setEnabled(false);
            }
        }
    });

    final JLabel cancel = new JLabel(new ImageIcon(Constants.getAsset("cancel.png")));
    cancel.setLayout(null);
    cancel.setBounds(229, 390, 122, 39);
    cancel.setBackground(Color.black);
    cancel.addMouseListener((OnMouseClick) e -> dispose());
    add(cancel);

    addWindowFocusListener(new WindowFocusListener() {
        private boolean gained = false;

        @Override
        public void windowGainedFocus(WindowEvent e) {
            gained = true;
        }

        @Override
        public void windowLostFocus(WindowEvent e) {
            if (gained) {
                dispose();
            }
        }
    });

    setSize(340, 432);
    setUndecorated(true);
    getContentPane().setBackground(Color.white);
    setResizable(false);
    getRootPane().setBorder(BorderFactory.createLineBorder(new Color(100, 100, 100)));
    Utils.setComponentLocationOnCenter(this);
    setVisible(true);
}