How do I set OFF a text underline?

I'm working on a basic word processor using Java. The thing is, I managed to underline the text I write by using TextAttribute, but I don't know how to set the text to plain. This is the code I used to initialize the TextAttribute:

    Font underLineFont = textInput.getFont();  
    Map attributes = underLineFont.getAttributes();
    attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);

and this is how I got to underline the text:

textInput.setFont(underLineFont.deriveFont(attributes));

Sorry if this question sounds stupid (still a beginner). But how can I set my text back to plain without the underlines?

Upvotes: 0

Views: 306

Answers (1)

Antoniossss
Antoniossss

Reputation: 32517

Try this:

Map attributes = textInput.getFont().getAttributes();
attributes.set(TextAttribute.UNDERLINE,-1);
textInput.setFont(textInput.getFont().deriveFont(attributes));

proof of concept:

public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setLayout(new FlowLayout());
    JLabel norm = new JLabel("Some text with some font");
    JLabel under = new JLabel("Underlined font");
    JLabel norm_again = new JLabel("Again font with no underline");

    f.getContentPane().add(norm);
    f.getContentPane().add(under);
    f.getContentPane().add(norm_again);
    f.pack();

    f.setLocationRelativeTo(null);
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Map attrs = norm.getFont().getAttributes();
    attrs.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
    under.setFont(norm.getFont().deriveFont(attrs));

    attrs = under.getFont().getAttributes();
    attrs.put(TextAttribute.UNDERLINE, -1);
    norm_again.setFont(under.getFont().deriveFont(attrs));
}

Result:

enter image description here

Upvotes: 2

Related Questions