I am trying to make a JLabel underlined. I searched everywhere, but I got nothing. Even in the properties, there is no option for underlining the JLabel. What can I do?
Asked
Active
Viewed 4.8k times
2 Answers
48
JLabel label = new JLabel("<HTML><U>YOUR TEXT HERE</U></HTML>");
label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
OR
JLabel label = new JLabel("Underlined Label");
Font font = label.getFont();
Map attributes = font.getAttributes();
attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
label.setFont(font.deriveFont(attributes));

xav
- 5,452
- 7
- 48
- 57

Abdelrahman Wahdan
- 2,056
- 4
- 36
- 43
-
15Don't forget to close your tags! – Clark Apr 09 '13 at 03:43
-
2@Clark it does not matter – Deval Khandelwal Oct 04 '14 at 15:14
-
7@devaldcool, even if it doesn't matter, a good practice should be followed at the very least to create good habits. Careless coding is the path to the dark side. Careless coding leads to bad habits. Bad habits lead to broken code. Broken code leads to suffering. – hfontanez Nov 07 '14 at 15:05
-
@hfontanez i m sure after reading your comment that u safely remove pendrive before ejecting it or hold a fork with your left hand...life is easy dude..do not waste time on closing tags or safely removing pendrives and eat like u have never eaten before – Deval Khandelwal Nov 08 '14 at 10:23
-
Where should I put these code? `initComponents()` is not editable, I am using Netbeans 8 – Newbie Mar 10 '16 at 07:29
-
It is not necessary to close `` tag. The doc use html text without closing the tag. https://docs.oracle.com/javase/tutorial/uiswing/components/html.html So I think it is totally acceptable. – WesternGun Sep 20 '17 at 09:21
36
JLabel label = new JLabel("Underlined Label");
Font font = label.getFont();
Map<TextAttribute, Object> attributes = new HashMap<>(font.getAttributes());
attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
label.setFont(font.deriveFont(attributes));
-
5+1. Also, label.getText() will now return the actual, intended text instead of HTML markup. – splungebob Apr 09 '13 at 04:10
-
4Better use `Map
attributes = new HashMap<>(font.getAttributes());` to avoid the compiler warning `unchecked call to put(k v) (...)`. – Petschko Jan 17 '17 at 20:13