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:tpp.TPPFrame.java

private static void browseHelp() {
    if (Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();
        try {/*from   w  w  w  .ja  va2  s  . c  om*/
            desktop.browse(new URI(TargetedProjectionPursuit.HELP_URL));
        } catch (Exception e) {
            // TODO: error handling
        }
    } else {
        // TODO: error handling
    }
}

From source file:net.rptools.maptool.client.MapTool.java

/**
 * Launch the platform's web browser and ask it to open the given URL. Note
 * that this should not be called from any uncontrolled macros as there are
 * both security and denial-of-service attacks possible.
 * //from w  ww .  j  ava  2s. c  om
 * @param url
 */
public static void showDocument(String url) {
    if (Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();
        URI uri = null;
        try {
            uri = new URI(url);
            desktop.browse(uri);
        } catch (Exception e) {
            MapTool.showError(I18N.getText("msg.error.browser.cannotStart", uri), e);
        }
    } else {
        String errorMessage = "msg.error.browser.notFound";
        Exception exception = null;
        String[] envvars = { "MAPTOOL_BROWSER", "BROWSER" };
        String param = envvars[0];
        boolean apparentlyItWorked = false;
        for (String var : envvars) {
            String browser = System.getenv(var);
            if (browser != null) {
                try {
                    param = var + "=\"" + browser + "\"";
                    Runtime.getRuntime().exec(new String[] { browser, url });
                    apparentlyItWorked = true;
                } catch (Exception e) {
                    errorMessage = "msg.error.browser.cannotStart";
                    exception = e;
                }
            }
        }
        if (apparentlyItWorked == false) {
            MapTool.showError(I18N.getText(errorMessage, param), exception);
        }
    }
}

From source file:localization.SplitterUI.java

private void openFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openFolderActionPerformed
    // TODO add your handling code here:
    String folderpath = filepath.getText();
    File fPath = new File(folderpath);
    if (folderpath.length() > 0) {
        File folder = null;/*from   w w w  . j  a va 2  s.c  om*/
        if (folderpath.endsWith(".lpu") && !fPath.isDirectory()) {
            folder = new File(folderpath.substring(0, folderpath.lastIndexOf("\\")));
        } else if (folderpath.endsWith(".zip") && !fPath.isDirectory()) {
            File zFile = new File(folderpath.substring(0, folderpath.lastIndexOf(".")));
            if (!zFile.exists()) {
                JOptionPane.showMessageDialog(this,
                        "Cannot find the unzip folder, please run it with zip file first.", "Folder Issue",
                        JOptionPane.WARNING_MESSAGE, null);
                return;
            }
            folder = new File(folderpath.substring(0, folderpath.lastIndexOf(".")));
        } else if (fPath.isDirectory()) {
            folder = fPath;
        }
        if (Desktop.isDesktopSupported()) {
            try {
                Desktop.getDesktop().open(folder);
            } catch (IOException ex) {
                Logger.getLogger(SplitterUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } else {
        String home = System.getProperty("user.home") + "\\Desktop";
        File folder = new File(home);
        if (Desktop.isDesktopSupported()) {
            try {
                Desktop.getDesktop().open(folder);
            } catch (IOException ex) {
                Logger.getLogger(SplitterUI.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:org.cirdles.ambapo.userInterface.AmbapoUIController.java

@FXML
private void clickGithubMenuItem(ActionEvent event) {
    final Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;

    try {/*from   w w  w.j a v  a2s  .  c o  m*/
        URI uri = new URI("https://github.com/CIRDLES/Ambapo");
        Desktop dt = Desktop.getDesktop();
        dt.browse(uri);
    } catch (IOException | URISyntaxException ex) {
    }
}

From source file:de.dal33t.powerfolder.Controller.java

/**
 * Starts controller with a special config file, and creates and starts all
 * components of PowerFolder.// ww w  . j  a  v  a 2  s . com
 *
 * @param filename
 *            The filename to uses as config file (located in the
 *            "getConfigLocationBase()")
 */
public void startConfig(String filename) {
    if (started) {
        throw new IllegalStateException("Configuration already started, shutdown controller first");
    }

    additionalConnectionListeners = Collections.synchronizedList(new ArrayList<ConnectionListener>());
    started = false;
    shuttingDown = false;
    threadPool = new WrappedScheduledThreadPoolExecutor(Constants.CONTROLLER_THREADS_IN_THREADPOOL,
            new NamedThreadFactory("Controller-Thread-"));

    // Initialize resource bundle eager
    // check forced language file from commandline
    if (commandLine != null && commandLine.hasOption("f")) {
        String langfilename = commandLine.getOptionValue("f");
        try {
            ResourceBundle resourceBundle = new ForcedLanguageFileResourceBundle(langfilename);
            Translation.setResourceBundle(resourceBundle);
            logInfo("Loading language bundle from file " + langfilename);
        } catch (FileNotFoundException fnfe) {
            logSevere("forced language file (" + langfilename + ") not found: " + fnfe.getMessage());
            logSevere("using setup language");
            Translation.resetResourceBundle();
        } catch (IOException ioe) {
            logSevere("forced language file io error: " + ioe.getMessage());
            logSevere("using setup language");
            Translation.resetResourceBundle();
        }
    } else {
        Translation.resetResourceBundle();
    }
    Translation.getResourceBundle();

    // loadConfigFile
    if (!loadConfigFile(filename)) {
        return;
    }

    boolean isDefaultConfig = Constants.DEFAULT_CONFIG_FILE.startsWith(getConfigName());
    if (isDefaultConfig) {
        // To keep compatible with previous versions
        preferences = Preferences.userNodeForPackage(PowerFolder.class);
    } else {
        preferences = Preferences.userNodeForPackage(PowerFolder.class).node(getConfigName());

    }

    // initialize logger
    // Enabled verbose mode if in config.
    // This logs to file for analysis.
    verbose = ConfigurationEntry.VERBOSE.getValueBoolean(this);
    initLogger();

    if (verbose) {
        ByteSerializer.BENCHMARK = true;
        scheduleAndRepeat(new Runnable() {
            @Override
            public void run() {
                ByteSerializer.printStats();
            }
        }, 600000L, 600000L);
        Profiling.setEnabled(false);
        Profiling.reset();
    }

    String arch = OSUtil.is64BitPlatform() ? "64bit" : "32bit";
    logFine("OS: " + System.getProperty("os.name") + " (" + arch + ')');
    logFine("Java: " + JavaVersion.systemVersion().toString() + " (" + System.getProperty("java.vendor") + ')');
    logFine("Current time: " + new Date());
    Runtime runtime = Runtime.getRuntime();
    long maxMemory = runtime.maxMemory();
    long totalMemory = runtime.totalMemory();
    logFine("Max Memory: " + Format.formatBytesShort(maxMemory) + ", Total Memory: "
            + Format.formatBytesShort(totalMemory));
    if (!Desktop.isDesktopSupported() && isUIEnabled()) {
        logWarning("Desktop utility not supported");
    }

    // If we have a new config. clear the preferences.
    clearPreferencesOnConfigSwitch();

    // Load and set http proxy settings
    HTTPProxySettings.loadFromConfig(this);

    // #2179: Load from server. How to handle timeouts?
    // Command line option -c http://are.de
    ConfigurationLoader.loadAndMergeCLI(this);
    // Config entry in file
    ConfigurationLoader.loadAndMergeConfigURL(this);
    // Read from installer temp file
    ConfigurationLoader.loadAndMergeFromInstaller(this);

    if (verbose != ConfigurationEntry.VERBOSE.getValueBoolean(this)) {
        verbose = ConfigurationEntry.VERBOSE.getValueBoolean(this);
        initLogger();
    }

    // Init paused only if user expects pause to be permanent or
    // "while I work"
    int pauseSecs = ConfigurationEntry.PAUSE_RESUME_SECONDS.getValueInt(getController());
    paused = PreferencesEntry.PAUSED.getValueBoolean(this)
            && (pauseSecs == Integer.MAX_VALUE || pauseSecs == 0);

    // Now set it, just in case it was paused in permanent mode.
    PreferencesEntry.PAUSED.setValue(this, paused);

    // Load and set http proxy settings again.
    HTTPProxySettings.loadFromConfig(this);

    // Initialize branding/preconfiguration of the client
    initDistribution();
    logFine("Build time: " + getBuildTime());
    logInfo("Program version " + PROGRAM_VERSION);

    if (getDistribution().getBinaryName().toLowerCase().contains("powerfolder")) {
        Debug.writeSystemProperties();
    }

    if (ConfigurationEntry.KILL_RUNNING_INSTANCE.getValueBoolean(this)) {
        killRunningInstance();
    }
    FolderList.removeMemberFiles(this);

    // Initialize plugins
    setupProPlugins();
    pluginManager = new PluginManager(this);
    pluginManager.init();

    // create node manager
    nodeManager = new NodeManager(this);

    // Only one task brother left...
    taskManager = new PersistentTaskManager(this);

    // Folder repository
    folderRepository = new FolderRepository(this);
    setLoadingCompletion(0, 10);

    // Create transfer manager
    // If this is a unit test it might have been set before.
    try {
        transferManager = transferManagerFactory.call();
    } catch (Exception e) {
        logSevere("Exception", e);
    }

    reconnectManager = new ReconnectManager(this);
    // Create os client
    osClient = new ServerClient(this);

    if (isUIEnabled()) {
        uiController = new UIController(this);
        if (ConfigurationEntry.USER_INTERFACE_LOCKED.getValueBoolean(this)) {
            // Don't let the user pass this step.
            new UIUnLockDialog(this).openAndWait();
        }
    }

    setLoadingCompletion(10, 20);

    // The io provider.
    ioProvider = new IOProvider(this);
    ioProvider.start();

    // Set hostname by CLI
    if (commandLine != null && commandLine.hasOption('d')) {
        String host = commandLine.getOptionValue("d");
        if (StringUtils.isNotBlank(host)) {
            InetSocketAddress addr = Util.parseConnectionString(host);
            if (addr != null) {
                ConfigurationEntry.HOSTNAME.setValue(this, addr.getHostName());
                ConfigurationEntry.NET_BIND_PORT.setValue(this, addr.getPort());
            }
        }
    }

    // initialize dyndns manager
    dyndnsManager = new DynDnsManager(this);

    setLoadingCompletion(20, 30);

    // initialize listener on local port
    if (!initializeListenerOnLocalPort()) {
        return;
    }
    if (!isUIEnabled()) {
        // Disable paused function
        paused = false;
    }

    setLoadingCompletion(30, 35);

    // Start the nodemanager
    nodeManager.init();
    if (!ProUtil.isRunningProVersion()) {
        // Nodemanager gets later (re) started by ProLoader.
        nodeManager.start();
    }

    setLoadingCompletion(35, 60);
    securityManager = new SecurityManagerClient(this, osClient);

    // init repo (read folders)
    folderRepository.init();
    logInfo("Dataitems: " + Debug.countDataitems(Controller.this));
    // init of folders takes rather long so a big difference with
    // last number to get smooth bar... ;-)
    setLoadingCompletion(60, 65);

    // start repo maintainance Thread
    folderRepository.start();
    setLoadingCompletion(65, 70);

    // Start the transfer manager thread
    transferManager.start();
    setLoadingCompletion(70, 75);

    // Initalize rcon manager
    startRConManager();

    setLoadingCompletion(75, 80);

    // Start all configured listener if not in paused mode
    startConfiguredListener();
    setLoadingCompletion(80, 85);

    // open broadcast listener
    openBroadcastManager();
    setLoadingCompletion(85, 90);

    // Controller now started
    started = true;
    startTime = new Date();

    // Now taskmanager
    taskManager.start();

    logInfo("Controller started");

    // dyndns updater
    /*
     * boolean onStartUpdate = ConfigurationEntry.DYNDNS_AUTO_UPDATE
     * .getValueBoolean(this).booleanValue(); if (onStartUpdate) {
     * getDynDnsManager().onStartUpdate(); }
     */
    dyndnsManager.updateIfNessesary();

    setLoadingCompletion(90, 100);

    // Login to OS
    if (Feature.OS_CLIENT.isEnabled()) {
        try {
            osClient.loginWithLastKnown();
        } catch (Exception e) {
            logWarning("Unable to login with last known username. " + e);
            logFiner(e);
        }
    }

    // Start Plugins
    pluginManager.start();

    // open UI
    if (isConsoleMode()) {
        logFine("Running in console");
    } else {
        logFine("Opening UI");
        openUI();
    }

    // Load anything that was not handled last time.
    loadPersistentObjects();

    setLoadingCompletion(100, 100);
    if (!isConsoleMode()) {
        uiController.hideSplash();
    }

    if (ConfigurationEntry.AUTO_CONNECT.getValueBoolean(this)) {
        // Now start the connecting process
        reconnectManager.start();
    } else {
        logFine("Not starting reconnection process. " + "Config auto.connect set to false");
    }
    // Start connecting to OS client.
    if (Feature.OS_CLIENT.isEnabled() && ConfigurationEntry.SERVER_CONNECT.getValueBoolean(this)) {
        osClient.start();
    } else {
        logInfo("Not connecting to server (" + osClient.getServerString() + "): Disabled");
    }

    // Setup our background working tasks
    setupPeriodicalTasks();

    if (MacUtils.isSupported()) {
        if (isFirstStart()) {
            MacUtils.getInstance().setPFStartup(true, this);
        }
        MacUtils.getInstance().setAppReOpenedListener(this);
    }

    if (pauseSecs == 0) {
        // Activate adaptive logic
        setPaused(paused);
    }
}

From source file:org.zaproxy.zap.extension.dynssl.DynamicSSLPanel.java

/**
 * writes the certificate to a temporary file and tells the OS to open it
 * using java.awrt.Desktop#open()/*from ww w  . ja v a  2 s.  c o m*/
 */
private void doView() {
    if (txt_PubCert.getDocument().getLength() < MIN_CERT_LENGTH) {
        logger.error("Illegal state! There seems to be no certificate available.");
        bt_view.setEnabled(false);
    }
    boolean written = false;
    File tmpfile = null;
    try {
        tmpfile = File.createTempFile(OWASP_ZAP_ROOT_CA_NAME, OWASP_ZAP_ROOT_CA_FILE_EXT);
        writePubCertificateToFile(tmpfile);
        written = true;
    } catch (final Exception e) {
        logger.error("Error while writing certificate data into temporary file.", e);
    }
    if (tmpfile != null && written) {
        if (Desktop.isDesktopSupported()) {
            try {
                Desktop.getDesktop().open(tmpfile);
            } catch (final IOException e) {
                logger.error("Error while telling the Operating System to open " + tmpfile, e);
            }
        }
    }
}

From source file:sc.fiji.kappa.gui.KappaMenuBar.java

/**
 * Creates a menu-bar and adds menu items to it
 *//*from w  ww  .j a  v a 2  s  .  c  o  m*/
public KappaMenuBar(Context context, KappaFrame frame) {
    context.inject(this);

    this.frame = frame;

    // File chooser for curve data
    FileNameExtensionFilter kappaFilter = new FileNameExtensionFilter("Kappa Files", "kapp");

    kappaLoad = new JFileChooser();
    kappaLoad.setFileFilter(kappaFilter);
    kappaLoad.setDialogTitle("Load Existing Curve Data");

    kappaSave = new JFileChooser();
    kappaSave.setFileFilter(kappaFilter);
    kappaSave.setDialogTitle("Save Curve Data");

    // Declares the file menu
    JMenu fileMenu = new JMenu("File");
    fileMenu.setMnemonic('F');

    /*
     * // Menu Items for file operations // Creates a new file chooser. Same native
     * image support as ImageJ since ImageJ // libraries are used. kappaOpen = new
     * JFileChooser(); FileNameExtensionFilter filter = new
     * FileNameExtensionFilter("Image Files", "tif", "tiff", "jpeg", "jpg", "bmp",
     * "fits", "pgm", "ppm", "pbm", "gif", "png", "dic", "dcm", "dicom", "lsm",
     * "avi"); kappaOpen.setFileFilter(filter);
     * 
     * JMenuItem openMenu = new JMenuItem("Open Image File");
     * openMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, DEFAULT_MASK));
     * openMenu.addActionListener(e -> { int returnVal =
     * kappaOpen.showOpenDialog(this.frame); if (returnVal ==
     * JFileChooser.APPROVE_OPTION) { openImageFile(kappaOpen.getSelectedFile()); }
     * }); fileMenu.add(openMenu);
     */

    JMenuItem openActiveMenu = new JMenuItem("Open Active Image");
    openActiveMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, DEFAULT_MASK));
    openActiveMenu.addActionListener(e -> {
        openActiveImage(context);
    });
    fileMenu.add(openActiveMenu);
    fileMenu.addSeparator();

    JMenuItem importROIsAsCurvesMenu = new JMenuItem("Import ROIs as curves");
    importROIsAsCurvesMenu.addActionListener(e -> {
        importROIsAsCurves(context);
    });
    fileMenu.add(importROIsAsCurvesMenu);
    fileMenu.addSeparator();

    JMenuItem loadMenu = new JMenuItem("Load Curve Data");
    loadMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, DEFAULT_MASK));
    loadMenu.addActionListener(e -> {
        // Handle open button action.
        int returnVal = kappaLoad.showOpenDialog(this.frame);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = kappaLoad.getSelectedFile();
            loadCurveFile(file);
        }
    });
    fileMenu.add(loadMenu);

    JMenuItem saveMenu = new JMenuItem("Save Curve Data");
    saveMenu.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, DEFAULT_MASK));
    saveMenu.addActionListener(e -> {

        String dirPath = frame.getImageStack().getOriginalFileInfo().directory;
        if (dirPath != null) {
            String kappaPath = FilenameUtils
                    .removeExtension(frame.getImageStack().getOriginalFileInfo().fileName);
            kappaPath += ".kapp";
            File fullPath = new File(dirPath, kappaPath);
            kappaSave.setSelectedFile(fullPath);
        }

        // Handles save button action.
        int returnVal = kappaSave.showSaveDialog(this.frame);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = kappaSave.getSelectedFile();
            // Appends a .kapp
            if (!file.getPath().toLowerCase().endsWith(".kapp")) {
                file = new File(file.getPath() + ".kapp");
            }
            saveCurveFile(file);
        }
    });
    fileMenu.add(saveMenu);

    this.add(fileMenu);

    // Menu Items for all the tools
    JMenu toolMenu = new JMenu("Tools");
    for (int i = 0; i < ToolPanel.NO_TOOLS; i++) {
        toolMenuItems[i] = new JMenuItem(ToolPanel.TOOL_MENU_NAMES[i]);
        toolMenuItems[i].setEnabled(false);
        toolMenuItems[i].setAccelerator(KeyStroke.getKeyStroke(ToolPanel.TOOL_MNEMONICS[i], 0));
        final int j = i;
        toolMenuItems[i].addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent event) {
                frame.getToolPanel().setSelected(j, true);
                frame.getScrollPane().setCursor(ToolPanel.TOOL_CURSORS[j]);
            }
        });
        toolMenu.add(toolMenuItems[i]);
    }

    // We also add a menu item for deleting Bezier Curves via the Backspace key.
    setDelete(new JMenuItem("Delete Curves"));
    getDelete().addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent event) {
            frame.deleteCurve();
        }
    });
    getDelete().setEnabled(false);
    getDelete().setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
    toolMenu.addSeparator();
    toolMenu.add(getDelete());

    setEnter(new JMenuItem("Enter Curve"));
    getEnter().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            frame.enterCurve();
        }
    });
    getEnter().setEnabled(false);
    getEnter().setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));
    toolMenu.add(getEnter());

    fit = new JMenuItem("Fit Curve");
    fit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            frame.fitCurves();
        }
    });
    fit.setEnabled(false);
    fit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, 0));
    toolMenu.add(fit);
    toolMenu.addSeparator();

    // TODO remove this later
    // JMenuItem runTestScript = new JMenuItem ("Run Testing Script");
    // runTestScript.addActionListener (new ActionListener(){
    // public void actionPerformed (ActionEvent event){
    // try{frame.testingScript();}
    // catch(IOException e){System.out.println("Script Error");}
    // }});
    // runTestScript.setAccelerator (KeyStroke.getKeyStroke(KeyEvent.VK_S, 0));
    // toolMenu.add(runTestScript);
    JCheckBoxMenuItem toggleCtrlPtAdjustment = new JCheckBoxMenuItem("Enable Control Point Adjustment");
    toggleCtrlPtAdjustment.setState(frame.isEnableCtrlPtAdjustment());
    toggleCtrlPtAdjustment.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            frame.setEnableCtrlPtAdjustment(!frame.isEnableCtrlPtAdjustment());
            ;
        }
    });
    toggleCtrlPtAdjustment.setEnabled(true);
    toolMenu.add(toggleCtrlPtAdjustment);

    this.add(toolMenu);

    // Navigation Menu
    // TODO FIX action listeners to these.
    JMenu navigateMenu = new JMenu("Navigate");
    prevFrame = new JMenuItem("Previous Frame");
    nextFrame = new JMenuItem("Next Frame");
    prevKeyframe = new JMenuItem("Previous Keyframe");
    nextKeyframe = new JMenuItem("Next Keyframe");
    prevFrame.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, ActionEvent.ALT_MASK));
    nextFrame.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, ActionEvent.ALT_MASK));
    prevKeyframe.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, DEFAULT_MASK));
    nextKeyframe.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, DEFAULT_MASK));
    prevFrame.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            frame.getControlPanel().getCurrentLayerSlider()
                    .setValue(Math.max(frame.getControlPanel().getCurrentLayerSlider().getValue() - 1,
                            frame.getControlPanel().getCurrentLayerSlider().getMinimum()));
        }
    });
    nextFrame.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            frame.getControlPanel().getCurrentLayerSlider()
                    .setValue(Math.min(frame.getControlPanel().getCurrentLayerSlider().getValue() + 1,
                            frame.getControlPanel().getCurrentLayerSlider().getMaximum()));
        }
    });
    prevKeyframe.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
        }
    });
    nextKeyframe.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
        }
    });
    prevFrame.setEnabled(false);
    nextFrame.setEnabled(false);
    prevKeyframe.setEnabled(false);
    nextKeyframe.setEnabled(false);
    navigateMenu.add(prevFrame);
    navigateMenu.add(nextFrame);
    navigateMenu.add(prevKeyframe);
    navigateMenu.add(nextKeyframe);
    this.add(navigateMenu);

    // Image options.
    JMenu imageMenu = new JMenu("Image");

    // Brightness and Contrast tool. Taken from ImageJ.
    adjustBrightnessContrast = new JMenuItem("Adjust Brightness/Contrast");
    adjustBrightnessContrast.setEnabled(false);
    adjustBrightnessContrast.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            ContrastAdjuster c = new ContrastAdjuster(frame);
            c.run("Brightness/Contrast...[C]");
        }
    });
    imageMenu.add(adjustBrightnessContrast);
    this.add(imageMenu);

    // Zoom-In and Zoom-Out Commands
    JMenu viewMenu = new JMenu("View");
    zoomIn = new JMenuItem("Zoom In");
    zoomOut = new JMenuItem("Zoom Out");
    zoomIn.addActionListener(new ZoomInListener(frame.getControlPanel()));
    zoomOut.addActionListener(new ZoomOutListener(frame.getControlPanel()));
    zoomIn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, DEFAULT_MASK));
    zoomOut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, DEFAULT_MASK));
    zoomIn.setEnabled(false);
    zoomOut.setEnabled(false);

    // Menu Item for showing bounding boxes
    setBoundingBoxMenu(new JCheckBoxMenuItem("Show Bounding Boxes"));
    getBoundingBoxMenu().setState(false);
    getBoundingBoxMenu().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent a) {
            frame.drawImageOverlay();
        }
    });
    getBoundingBoxMenu().setEnabled(false);

    // Menu Item for choosing the x-axis values for the curvature and intensity
    // display
    // For instance, you can display x vs. curvature, or current arc length vs
    // curvature, or the point index vs curvature
    // The default is the point index.
    distributionDisplay = DEFAULT_DISTRIBUTION_DISPLAY;
    JMenu xAxisSubmenu = new JMenu("Curve Distribution X-Axis:");
    ButtonGroup xAxisGroup = new ButtonGroup();
    JMenuItem xValue = new JCheckBoxMenuItem("X-Coordinate");
    JMenuItem curveLength = new JCheckBoxMenuItem("Arc Length");
    JMenuItem pointIndex = new JCheckBoxMenuItem("Point Index");
    xAxisGroup.add(xValue);
    xAxisGroup.add(curveLength);
    xAxisGroup.add(pointIndex);
    xAxisSubmenu.add(xValue);
    xAxisSubmenu.add(curveLength);
    xAxisSubmenu.add(pointIndex);
    xValue.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent a) {
            distributionDisplay = 0;
            frame.getInfoPanel().updateHistograms();
        }
    });
    curveLength.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent a) {
            distributionDisplay = 1;
            frame.getInfoPanel().updateHistograms();
        }
    });
    pointIndex.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent a) {
            distributionDisplay = 2;
            frame.getInfoPanel().updateHistograms();
        }
    });
    if (DEFAULT_DISTRIBUTION_DISPLAY == 0) {
        xValue.setSelected(true);
    } else if (DEFAULT_DISTRIBUTION_DISPLAY == 1) {
        curveLength.setSelected(true);
    } else {
        pointIndex.setSelected(true);
    }

    // Menu Item for scaling curve strokes when zooming in or out
    setScaleCurvesMenu(new JCheckBoxMenuItem("Scale Curve Strokes"));
    getScaleCurvesMenu().setState(true);
    getScaleCurvesMenu().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent a) {
            frame.drawImageOverlay();
        }
    });
    getScaleCurvesMenu().setEnabled(false);

    // Menu Item for image antialiasing
    setAntialiasingMenu(new JCheckBoxMenuItem("Enable Antialiasing"));
    getAntialiasingMenu().setState(false);
    getAntialiasingMenu().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent a) {
            frame.setScaledImage(frame.getControlPanel().getScaleSlider().getValue() / 100.0);
            frame.drawImageOverlay();
        }
    });
    getAntialiasingMenu().setEnabled(false);

    // Menu Item for displaying tangent and normal curves.
    setTangentMenu(new JCheckBoxMenuItem("Show Tangent and Normal Vectors"));
    getTangentMenu().setState(false);
    getTangentMenu().addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent a) {
            frame.drawImageOverlay();
        }
    });
    getTangentMenu().setEnabled(false);

    viewMenu.add(zoomIn);
    viewMenu.add(zoomOut);
    viewMenu.addSeparator();
    viewMenu.add(xAxisSubmenu);
    viewMenu.addSeparator();
    viewMenu.add(getScaleCurvesMenu());
    viewMenu.add(getTangentMenu());
    viewMenu.add(getBoundingBoxMenu());
    viewMenu.add(getAntialiasingMenu());
    this.add(viewMenu);

    // Sets a "Help" menu list
    JMenu helpMenu = new JMenu("Help");
    helpMenu.setMnemonic('H');

    // Adds an "About" option to the menu list
    JMenuItem aboutMenuItem = new JMenuItem("About...", 'A');
    aboutMenuItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            JOptionPane.showMessageDialog(frame, "Developed by the Brouhard lab, 2016-2017.",
                    KappaFrame.APPLICATION_NAME, JOptionPane.INFORMATION_MESSAGE);
        }
    });

    // Adds a link to the User Manual
    JMenuItem userManualLink = new JMenuItem("User Manual");
    userManualLink.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            try {
                if (Desktop.isDesktopSupported()) {
                    Desktop.getDesktop().browse(new URI(
                            "https://dl.dropboxusercontent.com/u/157117/KappaFrame%20User%20Manual.pdf"));
                }
            } catch (Exception e) {
                System.out.println("Incorrect URL Syntax");
            }
            ;
        }
    });

    // Adds all newly created menu items to the "Help" list
    helpMenu.add(userManualLink);
    helpMenu.add(aboutMenuItem);
    this.add(helpMenu);
}

From source file:entity.files.SYSFilesTools.java

/**
 * Diese Methode ermittelt zu einer gebenen Datei und einer gewnschten Aktion das passende Anzeigeprogramm.
 * Falls die Desktop API nicht passendes hat, werdne die lokal definierten Anzeigeprogramme verwendet.
 * <p>//from   w w  w.j  av a  2s.co  m
 * Bei Linux mssen dafr unbedingt die Gnome Libraries installiert sein.
 * apt-get install libgnome2-0
 *
 * @param file
 * @param action
 */
public static void handleFile(File file, java.awt.Desktop.Action action) {
    if (file == null) {
        return;
    }
    Desktop desktop = null;

    if (getLocalDefinedApp(file) != null) {
        try {
            Runtime.getRuntime().exec(getLocalDefinedApp(file));
        } catch (IOException ex) {
            OPDE.getLogger().error(ex);
        }
    } else {
        if (Desktop.isDesktopSupported()) {
            desktop = Desktop.getDesktop();
            if (action == Desktop.Action.OPEN && desktop.isSupported(Desktop.Action.OPEN)) {
                try {
                    desktop.open(file);
                } catch (IOException ex) {
                    OPDE.getDisplayManager().addSubMessage(
                            new DisplayMessage(SYSTools.xx("misc.msg.noviewer"), DisplayMessage.WARNING));
                }
            } else if (action == Desktop.Action.PRINT && desktop.isSupported(Desktop.Action.PRINT)) {
                try {
                    desktop.print(file);
                } catch (IOException ex) {
                    OPDE.getDisplayManager().addSubMessage(
                            new DisplayMessage(SYSTools.xx("misc.msg.noprintprog"), DisplayMessage.WARNING));
                }
            } else {
                OPDE.getDisplayManager().addSubMessage(
                        new DisplayMessage(SYSTools.xx("misc.msg.nofilehandler"), DisplayMessage.WARNING));
            }
        } else {
            OPDE.getDisplayManager().addSubMessage(
                    new DisplayMessage(SYSTools.xx("misc.msg.nojavadesktop"), DisplayMessage.WARNING));
        }
    }
}

From source file:org.interreg.docexplore.authoring.AuthoringMenu.java

public AuthoringMenu(final AuthoringToolFrame authoringTool) {
    this.tool = authoringTool;

    this.recent = new LinkedList<String>();
    readRecent();//from  www . j av a  2  s .  c o  m
    this.file = new JMenu(XMLResourceBundle.getBundledString("generalMenuFile"));
    add(file);

    newItem = new JMenuItem(new AbstractAction(XMLResourceBundle.getBundledString("generalMenuNew")) {
        public void actionPerformed(ActionEvent arg0) {
            newFile();
        }
    });
    loadItem = new JMenuItem(new AbstractAction(XMLResourceBundle.getBundledString("generalMenuLoad")) {
        public void actionPerformed(ActionEvent arg0) {
            load();
        }
    });
    saveItem = new JMenuItem(new AbstractAction(XMLResourceBundle.getBundledString("generalMenuSave")) {
        public void actionPerformed(ActionEvent arg0) {
            save();
        }
    });
    saveAsItem = new JMenuItem(new AbstractAction(XMLResourceBundle.getBundledString("generalMenuSaveAs")) {
        public void actionPerformed(ActionEvent arg0) {
            saveAs();
        }
    });
    exportItem = new JMenuItem(
            new AbstractAction(XMLResourceBundle.getBundledString("generalMenuExport") + "...") {
                public void actionPerformed(ActionEvent arg0) {
                    GuiUtils.blockUntilComplete(new ProgressRunnable() {
                        public void run() {
                            try {
                                authoringTool.readerExporter.doExport(authoringTool.editor.link);
                            } catch (Exception ex) {
                                ErrorHandler.defaultHandler.submit(ex);
                            }
                        }

                        public float getProgress() {
                            return (float) authoringTool.readerExporter.progress[0];
                        }
                    }, authoringTool.editor);
                }
            });
    webExportItem = new JMenuItem(
            new AbstractAction(XMLResourceBundle.getBundledString("generalMenuWebExport") + "...") {
                public void actionPerformed(ActionEvent arg0) {
                    GuiUtils.blockUntilComplete(new ProgressRunnable() {
                        public void run() {
                            try {
                                authoringTool.webExporter.doExport(authoringTool.editor.link);
                            } catch (Exception ex) {
                                ErrorHandler.defaultHandler.submit(ex);
                            }
                        }

                        public float getProgress() {
                            return (authoringTool.webExporter.copyComplete ? .5f : 0f)
                                    + (float) (.5 * authoringTool.webExporter.progress[0]);
                        }
                    }, authoringTool.editor);
                }
            });
    //      webExportItem = new JMenuItem(new AbstractAction("Web export") {public void actionPerformed(ActionEvent arg0)
    //      {
    //         GuiUtils.blockUntilComplete(new Runnable() {public void run()
    //         {
    //            try 
    //            {
    //               new WebStaticExporter().doExport(authoringTool.editor.link.getBook(authoringTool.editor.link.getLink().getAllBookIds().get(0)));
    //            }
    //            catch (Exception ex) {ErrorHandler.defaultHandler.submit(ex);}
    //         }}, authoringTool.editor);
    //      }});
    //      webExportItem.setEnabled(false);
    quitItem = new JMenuItem(new AbstractAction(XMLResourceBundle.getBundledString("generalMenuQuit")) {
        public void actionPerformed(ActionEvent arg0) {
            authoringTool.quit();
        }
    });
    buildFileMenu();

    JMenu edit = new JMenu(XMLResourceBundle.getBundledString("generalMenuEdit"));
    this.undoItem = new JMenuItem();
    undoItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                authoringTool.historyManager.undo();
            } catch (Exception ex) {
                ErrorHandler.defaultHandler.submit(ex);
            }
        }
    });
    edit.add(undoItem);
    this.redoItem = new JMenuItem();
    redoItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                authoringTool.historyManager.redo();
            } catch (Exception ex) {
                ErrorHandler.defaultHandler.submit(ex);
            }
        }
    });
    edit.add(redoItem);
    JMenuItem viewHistory = new JMenuItem(XMLResourceBundle.getBundledString("generalMenuEditViewHistory"));
    viewHistory.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            authoringTool.historyDialog.setVisible(true);
        }
    });
    edit.add(viewHistory);

    edit.addSeparator();

    edit.add(new JMenuItem(new AbstractAction(XMLResourceBundle.getBundledString("fixChars")) {
        public void actionPerformed(ActionEvent arg0) {
            Object res = JOptionPane.showInputDialog(tool, XMLResourceBundle.getBundledString("fixCharsMsg"),
                    XMLResourceBundle.getBundledString("fixChars"), JOptionPane.QUESTION_MESSAGE, null,
                    new Object[] { XMLResourceBundle.getBundledString("fixCharsWin"),
                            XMLResourceBundle.getBundledString("fixCharsMac") },
                    XMLResourceBundle.getBundledString("fixCharsWin"));
            if (res == null)
                return;
            try {
                convertPresentation(tool.defaultFile,
                        res.equals(XMLResourceBundle.getBundledString("fixCharsWin")) ? "ISO-8859-1"
                                : "x-MacRoman");
            } catch (Exception e) {
                ErrorHandler.defaultHandler.submit(e);
            }
            try {
                tool.editor.reset();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }));

    //TODO: remove!
    //      edit.add(new JMenuItem(new AbstractAction("hack!")
    //      {
    //         public void actionPerformed(ActionEvent e) {try
    //         {
    //            BookEditorView be = null;
    //            for (ExplorerView view : tool.editor.views)
    //               if (view instanceof BookEditorView)
    //                  be = (BookEditorView)view;
    //            Book book = be.curBook;
    //            int lastPage = book.getLastPageNumber();
    //            for (int pageNum = 1;pageNum <= lastPage;pageNum++)
    //            {
    //               Page page = book.getPage(pageNum);
    //               Set<Region> regions = page.getRegions();
    //               if (regions.size() > 2)
    //               {
    //                  Region highest = null;
    //                  int max = -1;
    //                  for (Region region : regions)
    //                     for (Point point : region.getOutline())
    //                        if (max < 0 || point.y < max)
    //                           {max = point.y; highest = region;}
    //                  Region middle = null;
    //                  max = -1;
    //                  for (Region region : regions)
    //                     if (region != highest)
    //                        for (Point point : region.getOutline())
    //                           if (max < 0 || point.y < max)
    //                              {max = point.y; middle = region;}
    //                  if (regions.size() > 3)
    //                  {
    //                     max = -1;
    //                     Region newMiddle = null;
    //                     for (Region region : regions)
    //                        if (region != highest && region != middle)
    //                           for (Point point : region.getOutline())
    //                              if (max < 0 || point.y < max)
    //                                 {max = point.y; newMiddle = region;}
    //                     middle = newMiddle;
    //                  }
    //                  MetaDataKey display = book.getLink().getKey("display", "");
    //                  for (Map.Entry<MetaDataKey, List<MetaData>> entry : highest.getMetaData().entrySet())
    //                     for (MetaData md : entry.getValue())
    //                        if (md.getType().equals(MetaData.textType))
    //                        {
    //                           String val = "<b>"+md.getString()+"</b>\n";
    //                           for (Map.Entry<MetaDataKey, List<MetaData>> entry2 : middle.getMetaData().entrySet())
    //                              for (MetaData md2 : entry2.getValue())
    //                                 if (md2.getType().equals(MetaData.textType) && TextElement.getStyle(md, tool.styleManager) == TextElement.getStyle(md2, tool.styleManager))
    //                                    val = val+"\n"+md2.getString();
    //                           md.setString(val);
    //                        }
    //                  boolean hasImage = false;
    //                  for (Map.Entry<MetaDataKey, List<MetaData>> entry2 : middle.getMetaData().entrySet())
    //                     for (MetaData md2 : entry2.getValue())
    //                        if (md2.getType().equals(MetaData.imageType))
    //                        {
    //                           MetaData imageMd = new MetaData(book.getLink(), display, md2.getType(), md2.getValue());
    //                           if (!hasImage)
    //                              BookImporter.insert(imageMd, highest, 0);
    //                           else BookImporter.insert(imageMd, highest, BookImporter.getHighestRank(highest)+1);
    //                           hasImage = true;
    //                        }
    //                  page.removeRegion(middle);
    //               }
    //            }
    //         }
    //         catch (Exception ex) {ex.printStackTrace();}System.out.println("done");}
    //      }));
    //      edit.add(new JMenuItem(new AbstractAction("hack!")
    //      {
    //         public void actionPerformed(ActionEvent e) {try
    //         {
    //            BookEditorView be = null;
    //            for (ExplorerView view : tool.editor.views)
    //               if (view instanceof BookEditorView)
    //                  be = (BookEditorView)view;
    //            Book book = be.curBook;
    //            int lastPage = book.getLastPageNumber();
    //            MetaDataKey display = book.getLink().getKey("display", "");
    //            for (int pageNum = 1;pageNum <= lastPage;pageNum++)
    //            {
    //               Page page = book.getPage(pageNum);
    //               Set<Region> regions = page.getRegions();
    //               for (Region region : regions)
    //               {
    //                  List<MetaData> mds = region.getMetaDataListForKey(display);
    //                     for (MetaData md : mds)
    //                        if (md.getType().equals(MetaData.textType))
    //                        {
    //                           String val = md.getString().trim();
    //                           if (!val.startsWith("<i>") || !val.endsWith("</i>"))
    //                              continue;
    //                           TextElement.getStyleMD(md).setString("4");
    //                           md.setString(val.substring(3, val.length()-4));
    //                           System.out.println(md.getString());
    //                        }
    //               }
    //            }
    //         }
    //         catch (Exception ex) {ex.printStackTrace();}System.out.println("done");}
    //      }));
    //      edit.add(new JMenuItem(new AbstractAction("hack!")
    //      {
    //         public void actionPerformed(ActionEvent e) {try
    //         {
    //            BookEditorView be = null;
    //            for (ExplorerView view : tool.editor.views)
    //               if (view instanceof BookEditorView)
    //                  be = (BookEditorView)view;
    //            Book book = be.curBook;
    //            int lastPage = book.getLastPageNumber();
    //            MetaDataKey display = book.getLink().getKey("display", "");
    //            for (int pageNum = 1;pageNum <= lastPage;pageNum++)
    //            {
    //               Page page = book.getPage(pageNum);
    //               Set<Region> regions = page.getRegions();
    //               for (Region region : regions)
    //               {
    //                  int max = BookImporter.getHighestRank(region);
    //                  for (int i=0;i<max;i++)
    //                  {
    //                     MetaData md1 = BookImporter.getAtRank(region, i);
    //                     if (md1 == null || !md1.getType().equals(MetaData.textType))
    //                        continue;
    //                     MetaData style1 = TextElement.getStyleMD(md1);
    //                     if (!style1.getString().equals("0"))
    //                        continue;
    //                     MetaData md2 = BookImporter.getAtRank(region, i+1);
    //                     if (md2 == null || !md2.getType().equals(MetaData.textType))
    //                        continue;
    //                     MetaData style2 = TextElement.getStyleMD(md2);
    //                     if (!style2.getString().equals("1"))
    //                        continue;
    //                     BookImporter.setRank(md1, i+1);
    //                     BookImporter.setRank(md2, i);
    //                     i++;
    //                  }
    //               }
    //            }
    //         }
    //         catch (Exception ex) {ex.printStackTrace();}System.out.println("done");}
    //      }));
    //      edit.add(new JMenuItem(new AbstractAction("hack!")
    //      {
    //         public void actionPerformed(ActionEvent e) {try
    //         {
    //            BookEditorView be = null;
    //            for (ExplorerView view : tool.editor.views)
    //               if (view instanceof BookEditorView)
    //                  be = (BookEditorView)view;
    //            Book book = be.curBook;
    //            MetaDataKey mini = book.getLink().getOrCreateKey("mini", "");
    //            MetaDataKey dim = book.getLink().getOrCreateKey("dimension", "");
    //            int lastPage = book.getLastPageNumber();
    //            for (int pageNum = 1;pageNum <= lastPage;pageNum++)
    //            {
    //               Page page = book.getPage(pageNum);
    //               List<MetaData> mds = page.getMetaDataListForKey(mini);
    //               if (mds != null)
    //                  for (MetaData md : mds)
    //                     page.removeMetaData(md);
    //               mds = page.getMetaDataListForKey(dim);
    //               if (mds != null)
    //                  for (MetaData md : mds)
    //                     page.removeMetaData(md);
    //               DocExploreDataLink.getImageDimension(page, true);
    //               DocExploreDataLink.getImageMini(page, false);
    //            }
    //         }
    //         catch (Exception ex) {ex.printStackTrace();}System.out.println("done");}
    //      }));

    add(edit);

    JMenu view = new JMenu(XMLResourceBundle.getBundledString("generalMenuView"));
    add(view);

    JMenuItem styles = new JMenuItem(XMLResourceBundle.getBundledString("styleEdit") + "...",
            ImageUtils.getIcon("pencil-24x24.png"));
    styles.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            authoringTool.styleManager.styleDialog.setVisible(true);
        }
    });
    view.add(styles);

    helpToggle = new JCheckBoxMenuItem(
            new AbstractAction(XMLResourceBundle.getBundledString("viewHelpToggle")) {
                public void actionPerformed(ActionEvent arg0) {
                    authoringTool.displayHelp = helpToggle.isSelected();
                    authoringTool.repaint();
                }
            });
    helpToggle.setSelected(tool.startup.showHelp);
    view.add(helpToggle);

    JMenu helpMenu = new JMenu(XMLResourceBundle.getString("management-lrb", "generalMenuHelp"));
    if (Desktop.isDesktopSupported()) {
        final Desktop desktop = Desktop.getDesktop();
        if (desktop.isSupported(Desktop.Action.OPEN)) {
            helpMenu.add(new AbstractAction(
                    XMLResourceBundle.getString("management-lrb", "generalMenuHelpContents")) {
                public void actionPerformed(ActionEvent e) {
                    try {
                        File doc = new File(DocExploreTool.getExecutableDir(), "MMT documentation.htm");
                        desktop.open(doc);
                    } catch (Exception ex) {
                        ErrorHandler.defaultHandler.submit(ex, true);
                    }
                }
            });
            helpMenu.add(new AbstractAction(
                    XMLResourceBundle.getString("management-lrb", "generalMenuHelpWebsite")) {
                public void actionPerformed(ActionEvent e) {
                    try {
                        File link = new File(DocExploreTool.getExecutableDir(), "website.url");
                        desktop.open(link);
                    } catch (Exception ex) {
                        ErrorHandler.defaultHandler.submit(ex, true);
                    }
                }
            });
        }
    }
    helpMenu.add(new AbstractAction(XMLResourceBundle.getString("management-lrb", "generalMenuHelpAbout")) {
        public void actionPerformed(ActionEvent e) {
            final JDialog splash = new JDialog(tool, true);
            splash.setLayout(new BorderLayout());
            SplashScreen screen = new SplashScreen("logoAT.png");
            splash.add(screen, BorderLayout.NORTH);
            screen.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseReleased(MouseEvent e) {
                    splash.setVisible(false);
                }
            });
            splash.setUndecorated(true);
            screen.setText(
                    "<html>DocExplore 2009-2014" + "<br/>Released under the CeCILL v2.1 license" + "</html>");
            splash.pack();
            splash.setAlwaysOnTop(true);
            GuiUtils.centerOnScreen(splash);
            splash.setVisible(true);
        }
    });
    add(helpMenu);

    historyChanged(authoringTool.historyManager);
    authoringTool.historyManager.addHistoryListener(this);
}

From source file:dr.app.bss.Utils.java

public static boolean isBrowsingSupported() {
    if (!Desktop.isDesktopSupported()) {
        return false;
    }/*from  w  w  w. j ava2  s .co  m*/
    boolean result = false;
    Desktop desktop = java.awt.Desktop.getDesktop();
    if (desktop.isSupported(Desktop.Action.BROWSE)) {
        result = true;
    }
    return result;

}