为什么强调不工作?

时间:2014-06-30 19:41:10

标签: java swing

我在启用toggleButton后写了一个简单的代码来强调文本。 禁用toggleButton后,将重置下划线。 但我没有看到下划线?

这是我的代码

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

但它不起作用。错误在哪里?

2 个答案:

答案 0 :(得分:4)

如果您使用JTextField而不是JTextPane,代码可以正常工作。

所以我想因为JTextPane被设计为与功能不起作用的样式属性一起使用。

您可以使用以下内容:

SimpleAttributeSet underline = new SimpleAttributeSet();
StyleConstants.setUnderline(underline, Boolean.TRUE);
StyledDocument doc = textPane.getStyledDocument();
doc.setCharacterAttributes(0, doc.getLength(), underline, false);

答案 1 :(得分:1)

你应该只使用html标签来强调你的按钮文本,而不是经历定义字体和地图等的过程。

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

应该更容易......