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?