2012-05-04 3 views
1

netbeans를 사용하는 프로젝트에서 작업 중입니다. jTextPane에서 텍스트의 여러 위치에있는 한 문자 만 색상을 지정하려고합니다. StyledDocument.setCharacterAttributes를 사용해 보았습니다. 그러나 적어도 2 자 이상을 색칠 할 수 있습니다. 원하는 것은 아닙니다. 순간 jTextPane에서 한 글자 만 색 지정

은이 코드를 사용하고 있습니다 :

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

어느 한 도움이 문제를 해결하기 위해 수 있습니다.

미리 감사드립니다.

답변

2

에 2. 그것에 length 파라미터 세트가 있습니다.

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; 
    } 
} 
+0

대단히 고마워요. 코드에 포함 시켰을 때 게시 한 코드가 완벽하게 작동했습니다. 그러나 for 루프의 characterAttributes를 설정하기 때문에 나에게도 똑같은 오래된 문제가 나타납니다. 적어도이 문제는 색칠 공부가 아니라는 것을 이해합니다. 그러나 그것은 내 자신의 코드에서 문제가 될 수 있습니다. 다시 감사합니다 –

0

setCharacterAttributes에 대한 설명서를 읽으셨습니까?

당신은 여기에 하나의 문자를 착색의 예입니다 1.

+0

나는 길이 매개 변수를 1로 변경했지만 아무 것도 수행하지 않습니다. 색깔은 변하지 않았다. –

+0

업데이트 된 코드를 게시 할 수 있습니까? – bvulaj

+0

StyledDocument doc = jTextPane1.getStyledDocument(); javax.swing.text.Style style = jTextPane1.addStyle ("Red", null); StyleConstants.setForeground (style, Color.RED); doc.setCharacterAttributes (5, 1, jTextPane1.getStyle ("Red"), true); –

관련 문제