2014-10-30 5 views
0

저는 현재 JTextPane에 스타일이 적용된 텍스트를 허용하고 편집 할 수없는 스타일의 텍스트를 JTextPane.에 표시하는 프로그램을 작성하고 있습니다. 실제로 입력과 표시 사이에서 문서를 구문 분석하려고합니다. 기본적으로 포맷을 유지하면서 DefaultStyledDocument을 두 개의 문서로 나눌 수 있기를 원합니다. 어떻게해야합니까?StyledDocument 나누기

SSCE를 나타낸 점 :

import java.awt.Color; 
import javax.swing.text.DefaultStyledDocument; 
import javax.swing.text.SimpleAttributeSet; 
import javax.swing.text.StyleConstants; 


public class SSCCE extends javax.swing.JFrame { 


    public SSCCE() { 
     initComponents(); 
     try { 
     DefaultStyledDocument doc = new DefaultStyledDocument(); 
     SimpleAttributeSet attr = new SimpleAttributeSet(); 
     StyleConstants.setBold(attr, true); 
     doc.insertString(0, "This is bold.\n\n", attr); 
     StyleConstants.setItalic(attr, true); 
     doc.insertString(doc.getLength() - 1, "This is bold and italicized.\n", attr); 
     doc.insertString(doc.getLength() - 1, "--\n", null); //This is a delimeter, for splitting the doucment 
     StyleConstants.setBold(attr, false); 
     StyleConstants.setForeground(attr, Color.red); 
     doc.insertString(doc.getLength() - 1, "This is italicized and red.\n", attr); 
     StyleConstants.setBold(attr, true); 
     StyleConstants.setItalic(attr, false); 
     doc.insertString(doc.getLength() -1 , "This is bold and red.\n", attr); 
     txpInput.setDocument(doc); //txpInput is a JTextPane 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 

    @SuppressWarnings("unchecked")      
    private void initComponents() { 

     jScrollPane1 = new javax.swing.JScrollPane(); 
     jPanel1 = new javax.swing.JPanel(); 
     jScrollPane2 = new javax.swing.JScrollPane(); 
     txpInput = new javax.swing.JTextPane(); 
     jScrollPane3 = new javax.swing.JScrollPane(); 
     txpOutput1 = new javax.swing.JTextPane(); 
     jLabel1 = new javax.swing.JLabel(); 
     btnOutput = new javax.swing.JButton(); 
     jScrollPane4 = new javax.swing.JScrollPane(); 
     txpOutput2 = new javax.swing.JTextPane(); 

     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

     jScrollPane2.setViewportView(txpInput); 

     txpOutput1.setEditable(false); 
     jScrollPane3.setViewportView(txpOutput1); 

     jLabel1.setText("Output:"); 

     btnOutput.setText("Output"); 
     btnOutput.addActionListener(new java.awt.event.ActionListener() { 
      public void actionPerformed(java.awt.event.ActionEvent evt) { 
       btnOutputActionPerformed(evt); 
      } 
     }); 

     txpOutput2.setEditable(false); 
     jScrollPane4.setViewportView(txpOutput2); 

     javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); 
     jPanel1.setLayout(jPanel1Layout); 
     jPanel1Layout.setHorizontalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(jPanel1Layout.createSequentialGroup() 
       .addContainerGap() 
       .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
        .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.TRAILING) 
        .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) 
        .addComponent(jScrollPane2) 
        .addGroup(jPanel1Layout.createSequentialGroup() 
         .addComponent(btnOutput, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE) 
         .addGap(0, 462, Short.MAX_VALUE)) 
        .addComponent(jScrollPane4)) 
       .addContainerGap()) 
     ); 
     jPanel1Layout.setVerticalGroup(
      jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(jPanel1Layout.createSequentialGroup() 
       .addContainerGap() 
       .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
       .addComponent(jLabel1) 
       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
       .addComponent(btnOutput) 
       .addGap(9, 9, 9) 
       .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
       .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) 
       .addContainerGap(79, Short.MAX_VALUE)) 
     ); 

     jScrollPane1.setViewportView(jPanel1); 

     javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
     getContentPane().setLayout(layout); 
     layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addComponent(jScrollPane1) 
     ); 
     layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addComponent(jScrollPane1) 
     ); 

     pack(); 
    }       

    private void btnOutputActionPerformed(java.awt.event.ActionEvent evt) {           
     //Comment out the body of this method to get code to run 
     //This needs to parse the text and output it to the two output JTextPanes 
     DefaultStyledDocument inputDoc = (DefaultStyledDocument) txpInput.getDocument(); 
     DefaultStyledDocument[] output = inputDoc.split("--"); //Invalid, is there an equivalent 
     txpOutput1.setDocument(ouput[0]); 
     txpOutput2.setDocument(ouput[1]); 
     this.validate(); 
     this.repaint(); 
    }           

    public static void main(String args[]) { 
     /* Set the Nimbus look and feel */ 
     try { 
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
       if ("Nimbus".equals(info.getName())) { 
        javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
        break; 
       } 
      } 
     } catch (ClassNotFoundException ex) { 
      java.util.logging.Logger.getLogger(SSCCE.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (InstantiationException ex) { 
      java.util.logging.Logger.getLogger(SSCCE.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (IllegalAccessException ex) { 
      java.util.logging.Logger.getLogger(SSCCE.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
      java.util.logging.Logger.getLogger(SSCCE.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     }  
     /* Create and display the form */ 
     java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       new SSCCE().setVisible(true); 
      } 
     }); 
    } 

    // Variables declaration - do not modify      
    private javax.swing.JButton btnOutput; 
    private javax.swing.JLabel jLabel1; 
    private javax.swing.JPanel jPanel1; 
    private javax.swing.JScrollPane jScrollPane1; 
    private javax.swing.JScrollPane jScrollPane2; 
    private javax.swing.JScrollPane jScrollPane3; 
    private javax.swing.JScrollPane jScrollPane4; 
    private javax.swing.JTextPane txpInput; 
    private javax.swing.JTextPane txpOutput1; 
    private javax.swing.JTextPane txpOutput2; 
    // End of variables declaration     
} 

참고 : 나는 넷빈즈 GUI 빌더, 따라서 긴 생성 된 코드를 사용합니다.

기본적으로이 예제에서는 일부 서식있는 텍스트를 JTextPane 입력에 입력했습니다. 그런 다음 서식을 잃지 않고 서식이 지정된 텍스트를 두 개의 출력 창으로 나눌 수 있어야합니다. SCCE에서 사용자가 "출력"버튼을 누르면 데이터가 복사되어 -- 행으로 분할됩니다. 예제에서 나는 존재하지 않는 split() 메서드를 사용했지만, 그 점을 이해할 수 있다고 생각합니다.

이 (이 특정 예를 들어) 예상 입력 : enter image description here

그리고 이것은 예상 출력 : enter image description here

내가 원래 this 질문은 가능한 대답을했다 생각했다. 그러나 나는 그것을 시도하고 그것이 작동하지 않는 것을 알았다. 마지막으로 스타일을 유지하면서 스타일이 지정된 문서를 분리하는 방법은 무엇입니까?

답변

0

동일한 콘텐츠 원본에서 StyledDocument 복사본을 2 부 만듭니다.

문서 분리 기호를 찾으십시오.

첫 번째 문서에서는 구분 기호 앞에있는 모든 내용을 제거하십시오.

두 번째 문서에서는 구분 기호 뒤에 모든 내용을 제거하십시오.

업데이트 : the code을 사용하여 문서를 병합 할 수 있지만 2 개의 대상 문서가 있고 필터 규칙에 따라 원본 문서의 삽입을 원하는 인스턴스로 리디렉션 할 수 있습니다.

+0

두 개의 문서를 얻으려면 어떻게해야합니까? JTextPane에서 문서를 가져오고 있습니다. _one_ 문서에 대한 참조 만 전달합니다. – DonyorM

+0

새로 만들 수 있습니다 - 새 EditorKitDependentDocument 또는 textPane.getEditorKit(). createDefaultDocument() – StanislavL