2014-04-06 5 views
0

나는 모양이 좋아 지도록 텍스트의 서식을 지정하는 더 큰 GUI의 일부를 디자인하려고합니다. 재미있는 방법으로 텍스트로 재생할 수 있어야합니다. 테두리 추가, 밑줄 긋기, 즉 장식 용도로 텍스트와 함께 할 수있는 모든 것. JTextPane은 이러한 목적을 달성하는 길입니까?JTextPane에서 여러 글꼴을 표시하려면 어떻게해야합니까?

아래 예제에서 decorateTextPane()은 두 줄의 텍스트를 다른 글꼴로 표시하고자합니다. 그러나 textPane.setFont()을 호출 할 때마다 창에서 기존 텍스트의 글꼴을 변경합니다. 당신이 수행 할 작업에 적합하기 때문에

public class OuterClass { 
    InnerClass inner = new InnerClass(); 

    private class InnerClass { 
     private JTextPane textPane = new JTextPane() 

     public InnerClass() { 
      StyledDocument doc = textPane.getStyledDocument(); 
      SimpleAttributeSet center = new SimpleAttributeSet(); 
      StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER); 
      doc.setParagraphAttributes(0, doc.getLength(), center, false); 
     } 
    } 

    public void decorateTextPane() { 
     inner.textPane.setFont(New Font("Times New Roman", Font.PLAIN, 15)); 
     inner.textPane.setText("First string"); 
     inner.textPane.setFont(New Font("Calibri", Font.PLAIN, 15)); 
     inner.textPane.append("\nSecond string"); //my textPane class defines an append method. 
    } 
} 

답변

0

useFont() 방법을 정의 내 현재의 접근 방식은이 지정된 글꼴을 사용합니다 텍스트를 추가하기 전에 그들을 사용. 그것은 작동하고 난 내용을 해요,하지만 사람이 더 좋은 답변이 있다면 나는 아직도

public class OuterClass { 
InnerClass inner = new InnerClass(); 

private class InnerClass { 
    private JTextPane textPane = new JTextPane(); 
    private Font firstFont = new Font("Times New Roman", Font.PLAIN, 18); 
    private Font secondFont = new Font("Calibri", Font.PLAIN, 14); 
    StyledDocument doc = textPane.getStyledDocument(); 
    SimpleAttributeSet aSet = new SimpleAttributeSet(); 

    public InnerClass() { 
     StyledDocument doc = textPane.getStyledDocument(); 
     SimpleAttributeSet center = new SimpleAttributeSet(); 
     StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER); 
     doc.setParagraphAttributes(0, doc.getLength(), center, false); 
    } 

    public void useFont1() { 
     StyleConstants.setFontFamily(aSet, firstFont.getFamily()); 
     StyleConstants.setFontSize(aSet, firstFont.getSize()); 
     doc.setParagraphAttributes(0, 0, aSet, false); 
    } 

    public void useFont2() { 
     StyleConstants.setFontFamily(aSet, secondFont.getFamily()); 
     StyleConstants.setFontSize(aSet, secondFont.getSize()); 
     doc.setParagraphAttributes(doc.getLength(), 0, aSet, false); 
    } 
} 

public void decorateTextPane() { 
    inner.useFont1(); 
    inner.textPane.setText("First string"); 
    inner.useFont2(); 
    inner.textPane.append("\nSecond string"); //my textPane class defines an append method. 
} 

}

:-) 매우 관심
1

당신은 대신 JTextPaneJEditorPane를 사용할 수 있습니다. :) 대답 Java JTextPane Change Font of Selected Text

에서

getDocument()와의 잡아 (그리고 분명히 JTextPane가 너무) JEditorPane로, 아래에 Document있다. 가능한 경우이를 StyledDocument으로 캐스팅하고 주어진 캐릭터에 setCharacterAttributes 등의 작업을 수행 할 수 있습니다.

예 : http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html