Reputation: 672
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?
Upvotes: 1
Views: 658
Reputation: 324108
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);
Upvotes: 4
Reputation: 591
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...
Upvotes: 1