1

I wrote a simple code for underlining the text after enabling the toggleButton. Reset of underlining will be actioned after disabling the toggleButton. But I don't see the underlining?

Here is my code

import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.util.Map;

import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.JToggleButton;

public class UnderlineIt {
  private JTextPane textPane;
  private JToggleButton button;
  private Font font;

    UnderlineIt() {
        JFrame frame = new JFrame("underline");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(new Dimension(200,200));

        textPane = new JTextPane();
        font = new Font("Serif",Font.BOLD+Font.ITALIC, 18);
        textPane.setFont(font); 
        textPane.setText("underlined");


        button = new JToggleButton("underline it!");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                if(button.isSelected()) {
                    Map attributes = font.getAttributes();
                    attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
                    textPane.setFont(font.deriveFont(attributes));
                } else {
                    Map attributes = font.getAttributes();
                    attributes.put(TextAttribute.UNDERLINE, -1);
                    textPane.setFont(font.deriveFont(attributes));
                }                                   
            }               
        });

        frame.add(textPane, BorderLayout.CENTER);
        frame.add(button, BorderLayout.SOUTH);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        new UnderlineIt();
    }
}

But it won't work. Where is the mistake?

Wooble
  • 87,717
  • 12
  • 108
  • 131
Ramses
  • 652
  • 2
  • 8
  • 30

2 Answers2

4

The code works fine if you use a JTextField instead of a JTextPane.

So I guess because JTextPane is designed to be used with style attributes that feature doesn't work.

You can use something like the following:

SimpleAttributeSet underline = new SimpleAttributeSet();
StyleConstants.setUnderline(underline, Boolean.TRUE);
StyledDocument doc = textPane.getStyledDocument();
doc.setCharacterAttributes(0, doc.getLength(), underline, false);
camickr
  • 321,443
  • 19
  • 166
  • 288
  • thank your for the note! Using different methods for the styling the text in JTextPane and JTextField? That really is annoying! – Ramses Jul 01 '14 at 08:42
1

You ought to just use html tags to underline your button text rather than go through the process of defining fonts, and maps and such.

if(button.isSelected()){
    textPane.setText("<u>Underlined text</u>")
} else {
    textPane.setText("Not Underlined");
}

that should be much easier...

TheJavaCoder16
  • 591
  • 4
  • 14