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?
Creating a HyperlinkHyperlink link = new Hyperlink(); link. setText("http://example.com"); link. setOnAction((ActionEvent e) -> { System. out.
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.
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 .
You can do that as follows, label. setText(label. getText() + "text u want to append");
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 */ } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With