对于个人项目,需要为用户提供一个简单的IDE,并在Java swing中突出显示语法。我正在使用插入jScrollPane中的jTextPane,因为此组件可以用多种颜色设置文本样式。结果,我不能使用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时,不会发生包装奇怪行为的单词。所以这是我的问题:
P.S。我已经读过java> 6中的自动换行和长单词问题,但是这个问题有所不同。
我终于找到了一个遇到jtextpane相同问题的人,并且可以在这里找到有效的解决方案:https://stackoverflow.com/a/14230668/9762750
这个想法是关于创建一个自定义EditorKit的,它可以对labelviews中的偏移量进行重新计算。使用此技巧可以很好地解决问题。