加下划线的JLabel

25 java swing netbeans jlabel

我试图让JLabel下划线.我到处搜索,但我一无所获.即使在属性中,也没有选项来强调JLabel.我能做什么?

Abd*_*dan 39

JLabel label = new JLabel("<HTML><U>YOUR TEXT HERE</U></HTML>");
label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
Run Code Online (Sandbox Code Playgroud)

要么

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));
Run Code Online (Sandbox Code Playgroud)

  • 别忘了关闭你的标签! (15认同)
  • @devaldcool,即使没关系,也应该遵循良好的做法,至少要养成良好的习惯.粗心编码是走向黑暗面的道路.粗心编码会导致不良习惯.坏习惯会导致代码破损.破碎的代码导致痛苦. (4认同)
  • @Clark没关系 (2认同)

Rei*_*eus 35

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));
Run Code Online (Sandbox Code Playgroud)

  • +1.此外,label.getText()现在将返回实际的预期文本而不是HTML标记. (5认同)
  • 更好地使用`Map <TextAttribute,Object> attributes = new HashMap <>(font.getAttributes());`以避免编译器警告`unchecked调用put(kv)(...)`. (3认同)