In html when we create a hyperlink and point over it ,then it automatically changes to a finger pointer.
So I was wondering can we achieve the same in java swings. Suppose I have a label on clicking which a new form pops-up.But I want that when the user points over the label it should change to finger pointer,showing that something will pop-up if its clicked.In this way we can differentiate that label with normal labels on the form i guess :).
But how to do something like this?
You can simply use the CSS cursor property with the value pointer to change the cursor into a hand pointer while hover over any element and not just hyperlink. In the following example when you place the cursor over the list item, it will change into a hand pointer instead of the default text selection cursor.
You can set cursor of JLabel to Cursor.HAND_CURSOR using below code :
JLabel label = new JLabel("https://stackoverflow.com"); label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
As said you'd want to call the setCursor()
method on the JLabel and set it to Cursor.Hand_CURSOR
to further this you can also underline the text to make it an HTML look alike link if you want :):
import java.awt.Color; import java.awt.Cursor; import java.awt.Desktop; import java.awt.Graphics; import java.awt.Insets; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.net.URI; import javax.swing.JLabel; /** * * @author ludovicianul */ public class URLLabel extends JLabel { private String url; public URLLabel() { this("",""); } public URLLabel(String label, String url) { super(label); this.url = url; setForeground(Color.BLUE.darker()); setCursor( new Cursor(Cursor.HAND_CURSOR)); addMouseListener( new URLOpenAdapter()); } public void setURL(String url) { this.url = url; } //this is used to underline the text @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.blue); Insets insets = getInsets(); int left = insets.left; if (getIcon() != null) { left += getIcon().getIconWidth() + getIconTextGap(); } g.drawLine(left, getHeight() - 1 - insets.bottom, (int) getPreferredSize().getWidth() - insets.right, getHeight() - 1 - insets.bottom); } private class URLOpenAdapter extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) { if (Desktop.isDesktopSupported()) { try { Desktop.getDesktop().browse(new URI(url)); } catch (Throwable t) { // } } } } }
Reference:
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