Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在jTextPane中仅为一个字符着色_Java_Textcolor - Fatal编程技术网

Java 在jTextPane中仅为一个字符着色

Java 在jTextPane中仅为一个字符着色,java,textcolor,Java,Textcolor,我正在使用netbeans进行一个项目。 我试图在jTextPane中仅为位于文本多个位置的一个字符上色。 我尝试使用StyledDocument.setCharacterAttributes,但它允许我为至少2个字符着色,这不是我想要的 目前我正在使用以下代码: StyledDocument doc = jTextPane1.getStyledDocument(); javax.swing.text.Style style = jTextPane1.addStyle("Red", null);

我正在使用netbeans进行一个项目。 我试图在jTextPane中仅为位于文本多个位置的一个字符上色。 我尝试使用StyledDocument.setCharacterAttributes,但它允许我为至少2个字符着色,这不是我想要的

目前我正在使用以下代码:

StyledDocument doc = jTextPane1.getStyledDocument();
javax.swing.text.Style style = jTextPane1.addStyle("Red", null);
StyleConstants.setForeground(style, Color.RED);
doc.setCharacterAttributes(5, 2, jTextPane1.getStyle("Red"), true); 
谁能帮助解决这个问题呢


提前谢谢。

您阅读了关于的文档了吗


length
参数设置为2。将其设置为1。

下面是一个为单个字符着色的示例

import java.awt.Color;
import javax.swing.*;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;

public class ColoredTextTest {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = initgui();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

    private static JFrame initgui() {
        JFrame frame = new JFrame("Test");
        JPanel panel = new JPanel();
        StyledDocument doc = (StyledDocument) new DefaultStyledDocument();
        JTextPane textpane = new JTextPane(doc);
        textpane.setText("Test");
        javax.swing.text.Style style = textpane.addStyle("Red", null);
        StyleConstants.setForeground(style, Color.RED);
        doc.setCharacterAttributes(0, 1, textpane.getStyle("Red"), true); 
        panel.add(textpane);
        frame.add(panel);
        return frame;
    }
}

是的,我将length参数改为1,但它什么也不做。颜色没有更改。StyledDocument doc=jTextPane1.getStyledDocument();javax.swing.text.Style Style=jTextPane1.addStyle(“红色”,null);设置前景(样式、颜色、红色);doc.setCharacterAttributes(5,1,jTextPane1.getStyle(“红色”),true);颜色没有变?还是彩色字符的数量没有改变?您最初声明的问题是为单个字符着色。对此表示抱歉。我的意思是彩色字符的数量没有改变。实际上,当我将长度参数更改为1时,根本没有彩色字符。非常感谢。当我将您发布的代码包含在我的代码中时,它工作得非常好。但是因为我在for循环中设置characterAttributes,所以它显示了相同的老问题。至少我知道问题不在着色语句中。但这在我自己的代码中可能是个问题。再次感谢你