在jTextPane中更改所选文本的颜色

时间:2013-09-30 16:13:04

标签: java swing colors jtextpane swing-highlighter

我正在使用JTextPane创建一个文本编辑器,允许用户更改所选文本的颜色。但是当用户选择文本时,则选择更改颜色(例如,红色)的选项,文本不会显示为红色,直到文本被取消选中。我尝试使用setSelectedTextColor来更改所选文本的颜色,但这不起作用,因为无论何时随后选择文本,都会将文本更改为红色。有没有办法让选定的文字显示为实际颜色?或者喜欢它在Word中的工作方式,它不是文本的实际颜色,但是当选择不同颜色的文本时,即使选择它们也会显示为不同的颜色。

我使用以下代码设置JTextPane和按钮,将所选文本更改为红色:

JButton redButton = new JButton(new StyledEditorKit.ForegroundAction("red", Color.RED));
redButton.setFocusable(false);
buttonPanel.add(redButton);

JTextPane设置为内容类型HTML并使用HTMLEditorKit:

p=new JTextPane();
p.setSize(300, 300);
kit = new HTMLEditorKit();
p.setEditorKit(kit);
p.setDocument(kit.createDefaultDocument());

p.setContentType("text/html");
p.setEditable(true);

如果您需要更多源代码来了解问题,请告诉我。谢谢!

4 个答案:

答案 0 :(得分:3)

听起来您可能正在使用除字体系列名称之外的其他内容。我重新考虑了这个example以使用JTextPane并看到了预期的结果。如上所述,动作需要字体系列名称,例如默认或face=SansSerif,由嵌套在StyledEditorKit中的FontFamilyAction类指定。

image

JTextPane textPane = new JTextPane();

答案 1 :(得分:3)

查看DefaultHighlightPainter的{​​{1}}内部类。

方法

DefaultHighlighter

如您所见,它使用 public void paint(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c) { Rectangle alloc = bounds.getBounds(); try { // --- determine locations --- TextUI mapper = c.getUI(); Rectangle p0 = mapper.modelToView(c, offs0); Rectangle p1 = mapper.modelToView(c, offs1); // --- render --- Color color = getColor(); if (color == null) { g.setColor(c.getSelectionColor()); } else { g.setColor(color); } getColor()。您可以扩展课程并调整高光绘画。

或者使用更简单的方法来覆盖getSelectionColor()的{​​{1}}。在该方法中,仅检查是否选择了文本并使用所选元素的属性来获得所需的ccolor。如果未选择任何内容,则返回JTextPane

更新: 实际上,在低级GlyphView上使用颜色进行选择     public void paint(Graphics g,Shape a){     ...            JTextComponent tc =(JTextComponent)c;             颜色selFG = tc.getSelectedTextColor();

getSelectionColor()

...

正如您所看到的,应用选择颜色与视图的默认颜色在SwingUtilities2.useSelectedTextColor(highlight,tc)中定义

来源http://kickjava.com/src/com/sun/java/swing/SwingUtilities2.java.htm

super.getSelectedColor()

所以使用颜色取决于L& F和画家。如果您定义了您的onw画家,则不会使用该颜色。

答案 2 :(得分:0)

更改所选文字颜色的最简单方法:

int start = textPane.getSelectionStart();
int end = textPane.getSelectionEnd();
int selectedLength = end - start;
StyleDocument style = pane.getStyledDocument();

//this give your attribute set of selected Text. 
AttributeSet oldSet = style.getCharacterElement(end-1).getAttributes();

//StyleContext for creating attribute set
StyleContext sc = StyleContext.getDefaultStyleContext();

// Attribute set which contains new color with old attributes
AttributeSet s = sc.addAttribute(oldSet, StyleConstants.Foreground, Color.RED);
//This set the color of the Text
style.setCharacterAttributes(start, selectedLength, s, true);

答案 3 :(得分:0)

添加我的视图。这可能比上面的方法更简单。

    JEditorPane ep = new JEditorPane() {
        @Override
        public Color getSelectionColor() {
            return COLOR_YOU_WANT;
        }

        @Override
        public Color getSelectedTextColor() {
            return COLOR_YOU_WANT;
        }
    };