-1

I am trying to make a function that allows you to navigate to a webpage. I can how to run the function, I just don't know how to write the part of the program that accesses the webpage. Here is the code that I am using to access the function via a JButton. I would like the program to work on multiple platforms. All of the solutions I have found to this, I either don't understand well enough to modify to my needs, or it isn't multi-platform.

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        JButton google = new JButton("Google");
        linux.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                        openURL("http://www.google.com/"); 
                }
        } );
        JButton stackoverflow = new JButton("Stackoverflow");
        JButton blah = new JButton("blah");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        panel.add(linux);
        panel.add(osx);
        panel.add(windows);
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }

Yes I am aware the last two buttons do nothing.

Here is what I have tried so far:

    public static void openURL(String url) {
        String osName = System.getProperty("os.name");
        try {
            if (osName.startsWith("Windows"))
                Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
            else {
                String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape", "chrome" };
                String browser = null;
                for (int count = 0; count < browsers.length && browser == null; count++)
                    if (Runtime.getRuntime().exec(new String[] {"which", browsers[count]}).waitFor() == 0)
                    browser = browsers[count];
                Runtime.getRuntime().exec(new String[] {browser, url});
        }
    }
        catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Error in opening browser" + ":\n" + e.getLocalizedMessage());
        }
    }

Unfortunately, I don't understand what this does, or how to change it to my needs.

If possible could you explain your solution so that I can understand how it works? Thanks.

nachokk
  • 14,363
  • 4
  • 24
  • 53

1 Answers1

2

You can use Desktop class which allows Java applications to interact with default applications associated with specific file types on the host platform. Here you have a tutorial on How to integrate with the Desktop class.

Remember:

Use the isDesktopSupported() method to determine whether the Desktop API is available

I made a quick example.

import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class DesktopTest {

    private JPanel panel;

    public DesktopTest() {
        panel = new JPanel();

        ActionListener listener = new OpenUrLAction();

        JButton googleButton = new JButton("google");
        googleButton.setActionCommand("http://www.google.com");
        googleButton.addActionListener(listener);

        JButton stackOverButton = new JButton("stackOverflow");
        stackOverButton.setActionCommand("http://www.stackoverflow.com");
        stackOverButton.addActionListener(listener);

        panel.add(googleButton);
        panel.add(stackOverButton);

    }

    public JPanel getPanel() {
        return panel;
    }

    private class OpenUrLAction implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (Desktop.isDesktopSupported()) {
                try {
                                        Desktop desktop = Desktop.getDesktop();
                    desktop.browse(new URI(e.getActionCommand()));
                } catch (IOException | URISyntaxException e1) {
                    JOptionPane.showMessageDialog(null,
                            "An error happen " + e1.getMessage());
                }
            }

        }

    }

    /**
     * Create the GUI and show it. For thread safety, this method should be
     * invoked from the event-dispatching thread.
     */
    private static void createAndShowGUI() {
        // Create and set up the window.
        JFrame frame = new JFrame("DesktopExample");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        frame.setLocationByPlatform(Boolean.TRUE);
        frame.add(new DesktopTest().getPanel());

        // Display the window.
        frame.pack();
        frame.setVisible(Boolean.TRUE);
    }

    public static void main(String[] args) {
        // Schedule a job for the event-dispatching thread:
        // creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

}

If you don't find this useful , you can find some workaround in this answer

Community
  • 1
  • 1
nachokk
  • 14,363
  • 4
  • 24
  • 53