Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add hyperlink in JLabel?

What is the best way to add a hyperlink in a JLabel? I can get the view using html tags, but how to open the browser when the user clicks on it?

like image 802
amit Avatar asked Feb 09 '09 10:02

amit


People also ask

How do you add a hyperlink in Java?

Creating a HyperlinkHyperlink link = new Hyperlink(); link. setText("http://example.com"); link. setOnAction((ActionEvent e) -> { System. out.

How do you make text clickable in Java?

If you are using a JTextPane you can use the insertComponent() method to insert a new JLabel that is of the same font as the JTextPane font and you can customize the JLabel the way you want like setting the cursor to hand cursor thereby giving it a clickable look and feel.

How do you make a clickable label in Java?

1:- Implement your class containing the JLabel with MouseListener interface 2:- add MouseListener to your JLabel 3:-Override mouseClicked Event in your class 4:- In mouseClicked Even't body add your code to open a new JFrame/Frame .

How do I add text to a JLabel?

You can do that as follows, label. setText(label. getText() + "text u want to append");


1 Answers

You can do this using a JLabel, but an alternative would be to style a JButton. That way, you don't have to worry about accessibility and can just fire events using an ActionListener.

  public static void main(String[] args) throws URISyntaxException {     final URI uri = new URI("http://java.sun.com");     class OpenUrlAction implements ActionListener {       @Override public void actionPerformed(ActionEvent e) {         open(uri);       }     }     JFrame frame = new JFrame("Links");     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     frame.setSize(100, 400);     Container container = frame.getContentPane();     container.setLayout(new GridBagLayout());     JButton button = new JButton();     button.setText("<HTML>Click the <FONT color=\"#000099\"><U>link</U></FONT>"         + " to go to the Java website.</HTML>");     button.setHorizontalAlignment(SwingConstants.LEFT);     button.setBorderPainted(false);     button.setOpaque(false);     button.setBackground(Color.WHITE);     button.setToolTipText(uri.toString());     button.addActionListener(new OpenUrlAction());     container.add(button);     frame.setVisible(true);   }    private static void open(URI uri) {     if (Desktop.isDesktopSupported()) {       try {         Desktop.getDesktop().browse(uri);       } catch (IOException e) { /* TODO: error handling */ }     } else { /* TODO: error handling */ }   } 
like image 100
McDowell Avatar answered Sep 21 '22 02:09

McDowell