简体   繁体   中英

Remove the underline from a JLabel text

I used to underline a JLabel text once clicked this code:

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));

So now I need to restore it to its first state (without underline) once another JLabel is clicked what shall I change?

Thank you in advanced!

It turns out that TextAttribute.UNDERLINE_OFF is not a real constant. So I consulted the TextAttribute#UNDERLINE documentation :

 public static final TextAttribute UNDERLINE

Attribute key for underline. Values are instances of Integer . The default value is -1 , which means no underline.

The constant value UNDERLINE_ON is provided.

The underline affects both the visual bounds and the outline of the text.

And it turns out the default value is -1 . So to revert the text back to not being underlined just use:

attributes.put(TextAttribute.UNDERLINE, -1);

The answer attributes.put(TextAttribute.UNDERLINE, -1); doesn't work for me.

But:

label.setFont(new Font(font.getName(), font.getStyle(), font.getSize())); 

works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM