Как исправить странное поведение переноса слов в java swing jtextpane с DocumentFilter и стилем? - PullRequest
0 голосов
/ 05 октября 2019

Для личного проекта необходимо предоставить пользователям простую IDE с подсветкой синтаксиса в java swing. Я использую jTextPane, вставленный в jScrollPane, так как этот компонент может стилизовать текст разными цветами. Как следствие, я не могу использовать jTextArea.

Я решил использовать пользовательский DocumentFilter для работы с новым текстом и выделения его при необходимости. Однако я заметил, что при этом ввод символов в одной строке может изменить перенос слов в других строках. Это приводит к очень странному поведению, так как добавление одного символа влияет на несколько строк.

Вот MWE, который воспроизводит проблему:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mbrebion.jtextpanetest;

import java.awt.Color;
import javax.swing.JTextPane;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;

/**
 *
 * @author mbrebion
 */
public class mainWindow extends javax.swing.JFrame {

    /**
     * Creates new form mainWindow
     */
    public mainWindow() {
        initComponents();
        CustomDocumentFilter cdf = new CustomDocumentFilter(jTextPane1);
        ((AbstractDocument) jTextPane1.getDocument()).setDocumentFilter(cdf);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jScrollPane1.setViewportView(jTextPane1);

        jButton1.setText("reStyle");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(55, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap(56, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, 0)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
                .addGap(2, 2, 2)
                .addComponent(jButton1))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        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(mainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(mainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(mainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(mainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new mainWindow().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration                   
}

class CustomDocumentFilter extends DocumentFilter {

    protected AttributeSet blackAttributeSet;
    protected StyledDocument styledDocument;
    protected JTextPane jtp;

    public CustomDocumentFilter(JTextPane jtp) {
        this.jtp = jtp;
        styledDocument = jtp.getStyledDocument();
        StyleContext styleContext = StyleContext.getDefaultStyleContext();
        blackAttributeSet = styleContext.addAttribute(styleContext.getEmptySet(), StyleConstants.Foreground, Color.BLACK);
    }

    @Override
    public void insertString(FilterBypass fb, int offset, String text, AttributeSet attributeSet) throws BadLocationException {
        super.insertString(fb, offset, text, attributeSet);
        styledDocument.setCharacterAttributes(0, jtp.getText().length(), blackAttributeSet, true);
    }

    @Override
    public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
        super.remove(fb, offset, length);
        styledDocument.setCharacterAttributes(0, jtp.getText().length(), blackAttributeSet, true);
    }

    @Override
    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attributeSet) throws BadLocationException {
        super.replace(fb, offset, length, text, attributeSet);
        styledDocument.setCharacterAttributes(0, jtp.getText().length(), blackAttributeSet, true);
    }

}

Я заметил, что перенос словстранное поведение не происходит, когда пользовательский DocumentFilter не используется. Итак, вот мои вопросы:

  • Есть ли способ исправить эту проблему?
  • Если нет, возможно ли (и легко?) Выполнять подсветку синтаксиса без фильтра документа?

PS Я читал о проблеме с переносом слов и длинными словами в java> 6, но эта проблема другая.

1 Ответ

0 голосов
/ 05 октября 2019

Наконец-то я нашел кого-то, кто столкнулся с той же проблемой с jtextpane, и здесь можно найти рабочее решение: https://stackoverflow.com/a/14230668/9762750

Идея заключается в создании пользовательского EditorKit, который обеспечивает пересчет смещений в представлениях меток,Использование этого трюка отлично решило проблему.

...