Java 在JTextPane中不使用HTML将单行加粗
我试图在JTextPane中加粗一行,但我所做的一切都不起作用。 我试着用一种新的粗体字体写这行字,但没用Java 在JTextPane中不使用HTML将单行加粗,java,html,swing,jtextarea,Java,Html,Swing,Jtextarea,我试图在JTextPane中加粗一行,但我所做的一切都不起作用。 我试着用一种新的粗体字体写这行字,但没用 Font font = new Font("Consolas", Font.BOLD, 11); textPane.setFont(font); textPane.setText(textPane.getText() + "\n" + getTimeStamp() + sender + ": " + message);
Font font = new Font("Consolas", Font.BOLD, 11);
textPane.setFont(font);
textPane.setText(textPane.getText() + "\n" + getTimeStamp() + sender + ": " + message);
textPane.setFont(defaultFont);
如何执行此操作?最简单的方法是从JTextPane获取StyledDocument,并使用setCharacterAttributes()方法 StyledDocument对象上的setCharacterAttributes方法允许您为特定字符范围设置一组属性,这些属性可以包括粗体 见 一些示例代码可能是
// set chars 4 to 10 to Bold
SimpleAttributeSet sas = new SimpleAttributeSet();
StyleConstants.setBold(sas, true);
textPane.getStyledDocument().setCharacterAttributes(4, 6, sas, false);
需要注意的是确保您使用的字体系列在您的系统上有一个加粗字体。我开始使用Monaco(在OSX上),它只包含一个常规字体。在我切换到Menlo之前,一切都不起作用,它有一个Menlo粗体条目 下面是一些基于Oracle示例的代码
StyledDocument document = textPane.getStyledDocument ();
Style defaultStyle =
StyleContext.getDefaultStyleContext ().getStyle (StyleContext.DEFAULT_STYLE);
Style regular = document.addStyle ("regular", defaultStyle);
StyleConstants.setBackground (regular, backgroundColor);
StyleConstants.setFontFamily (regular, "Menlo");
StyleConstants.setFontSize (regular, 14);
blackStyle = document.addStyle ("BlackStyle", regular);
StyleConstants.setForeground (blackStyle, Color.black);
redStyle = document.addStyle ("RedStyle", regular);
StyleConstants.setForeground (redStyle, Color.red);
StyleConstants.setBold (redStyle, true);
你能给我举个例子吗?那太好了。现在有一个给你。为什么要问代码,这里+1很乐意帮忙。秋千有时会成为雷区!另一个问题:我第一次运行这个方法时,它是有效的。钮扣线变粗了。但下次我运行该方法时,它会添加另一行文本,但所有内容都会恢复正常(非粗体)。