I need to create a shortcut with Java Swing that you can click and open the default browser on the desktop and redirect it to a specific URL. My code may open the browser but not redirect it to the correct URL (loading the default source page). My test code is:
import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.io.IOException; import java.net.*; public class LinkTest extends JFrame { public LinkTest() { JPanel p = new JPanel(); JLabel link = new JLabel("Click here"); link.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); link.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() > 0) { if (Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); try { URI uri = new URI("http://www.bbc.co.uk"); desktop.browse(uri); } catch (IOException ex) { ex.printStackTrace(); } catch (URISyntaxException ex) { ex.printStackTrace(); } } } } }); p.add(link); getContentPane().add(BorderLayout.NORTH, p); } public static void main(String[] args) { LinkTest linkTest = new LinkTest(); linkTest.setSize(640,100); linkTest.show(); } }
How can I open the default browser and redirect it to the correct URL using Java Swing?
java browser swing hyperlink jlabel
Randomize Dec 29 '11 at 2:55 a.m. 2011-12-29 14:55
source share