如何设置下一个文本为粗体动作监听器[java]

时间:2015-12-03 02:29:37

标签: java swing jeditorpane

我正在尝试为文本编辑器创建一个粗体函数,但我不知道如何将您键入的下一个文本设置为粗体格式。(我只想清楚这不是关于将所选文本设置为粗体,而是将您在将来键入的文本设置为粗体)我正在尝试

JEditorPane feild2 = new JEditorPane("text/html","");
JButton Button=new JButton("B");
Button.addActionListener(new ActionListener(){

@Override
public void actionPerformed(ActionEvent arg4) {
    int e=0;
    if(arg4.getSource()==Button&&e==0){
        feild2.setText(feild2.getText()+ "<b>");
        e=1;
    }
    else if(arg4.getSource()==Button&&e==1){
        feild2.setText(feild2.getText()+ "</b>");
        e=0;
    }
}

});

但那不起作用。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

使用StyledEditorKit提供的默认操作:

JButton button = new JButton( new StyledEditorKit.BoldAction() );

如果单击带有所选文本的按钮,则文本将变为粗体。

如果在未选择任何文本时单击该按钮,则插入符号处插入的文本将为粗体。