JTextPane自动换行问题

时间:2012-11-30 08:05:31

标签: java swing word-wrap jtextpane

我在用于维基源编辑的应用程序中使用JTextPane。我添加了一个简单的拼写检查功能,它通过StyledDocument.setCharacterAttributes将字符属性更改为不同的样式来强调拼写错误的单词。

只使用了这两种样式:默认和'拼错'。文本编辑器控件执行自动换行,这是预期的行为。

我的问题是有些情况(并非总是如此,但可以通过特定的维基文档重现)这个字符属性改变以某种方式禁用自动换行。更具体地说,我从文档的中间删除三行,并在下次运行拼写检查时,将字符属性重置为默认样式(在重新运行拼写检查之前),自动换行功能被禁用,它仍然是办法。如果我撤消删除,自动换行将恢复正常。

评论重置样式的单行:

editorPane.getStyledDocument().setCharacterAttributes(0, editorPane.getStyledDocument().getLength(), defaultStyle, true);

解决了这个问题。

编辑1

我已将问题提取到一个简单的测试用例中。对于长线,很抱歉,示例文本对于重现错误非常重要(它已被随机化):

package jtextpanebug;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.WindowConstants;
import javax.swing.text.Style;


public class DemoFrame extends javax.swing.JFrame {

    private final JButton btResetStyle;
    private final JScrollPane scrollPane;
    private final JTextPane textPane;    
    private final Style defaultStyle;

    public DemoFrame() {
        // Creating a simple form with a scrollable text pane and a button
        scrollPane = new JScrollPane();
        textPane = new JTextPane();
        btResetStyle = new JButton();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

        // The text pane's text is the scrambled version of my original test data,
        // it is important because the problem depends on the pane's text
        // (not every text makes it wrong)
        textPane.setText("= Gernela Stuff Dogo to Wnko Obuat Oebrfe Disytung hte Iidnividal Oitpcs =\n\n== Elmyonrogit ==\n\n'''memidtaie-ngiebhro opnits''' - 2 points, \nwihhc nac eb ense ot eb mmiieadte hnigeorbs fo haec othre. \nThere si no strict | cxeat defiintoin. \nEth etipcur owebl shsow sa an example optins dna the rispa \nienbg mimedtiea iebnghsor ear ncnoetced.\n\n[[Amieg:einogrhb_pinsot.pgn]]\n\n'''enihgorb optnsi distacne''' - het avaeegr of sdntaisce \nderemitedn by het mimeidate-hieobngr tonpi ipras. \n\n'''lalw''' - a iotpntes nepgesnietrr a llwa, with toerh orwds: 2 apraelll, \nevyr sloce sraufce picsee. Heer is an xamelpe. \nIt is eualgttandri ofr eterbt zisiuaitovlan.\n\n[[Gimae:llwa.npg]]\n\n'''addtaiilon emmory reeueimtnqr of na laigorthm''' - \n(eth kepa mmeory suaeg fo teh nltpiaciapo ndirug the excteouin of eht grlaotihm) - \n(hte moeymr sueag fo hte loragitmh befoer ro ftrea eht ucxeeiont of the laogrihmt)\n\n== Het Input Pnoitset Ash to Repnrsete Ufscear Arsnoelbay Elwl ==\n\nIf tno efisciped toehrwsie yb hte cdoritnpsei of an aoglirthm, \nhetn hte eqtunrmeersi of it are heste:\n\n* Ifsrt fo all the poisentt umst reprseent urfseac, not urvec ro uvomel or nayithng eesl.\n* Awlls aym otn eb tniehnr tanh at least 3 * fo ienhbgro-tpoin-sidenact.\n* Dseeg amy ton be rhserap tnha 70 grdesee (as het agnle fo eht trmeaial) nda husdol be ta tleas 290 redeseg (ni caes fo cnvocae eedgs).\n* Onpti edintsy amy ont vayr oto humc \n** Het angre fo the coall ption desitnsei of a igsenl pisnotte nutip ushold eb sallm. Ahtt is: teh orait of het oclla oitnp idsentise oarund any 2 ipnost lsdhou eb lmitied.\n** Hte lcoal noipt deisynt ushlod otn ahencg sdduelyn (gliftyscaiinn ni a hotsr idnsteac). \n\nYreftntunaoul the largoimths cna tno yb ethmsevesl \nhcekc these qutenmeserir nda usjt yden rnuning, \nso it si eth rseu's iyponerissbtil to ton extucee an raltghomi no a itseopnt \nthat does ont mete het aogitmlhr's terieseurmnq.\n\nIf eth rmeteriuqen fo na airlgmoth on its npuit is ont mte, then tobh hte ueavbhior nad hte srluet fo hte alghoritms si dinfeuned. \nTeh loirgamth amy nru rfo iinfntie long imet or rodpuce evry abd rselut, ro a eruslt htat oolsk good btu is nicrtroec. Ni htis scea rtehe si tno nay aguntreee toabu the tmniatreion of the iralgtmho ro eht lqutaiy fo the sreltu ecxept htat the nptapalcioi iwll ont carsh.\n");
        scrollPane.setViewportView(textPane);

        getContentPane().add(scrollPane);

        btResetStyle.setText("Reset style");
        btResetStyle.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                btResetStyleActionPerformed(evt);
            }
        });
        getContentPane().add(btResetStyle);

        pack();

        // The default style, the problem happens when we reset the full document
        // to it:
        defaultStyle = textPane.addStyle("default", null);        
    }

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

        // When the button is pressed we reset the full document to the default
        // style. In the original application this was periodically done as 
        // part of the spell checking
        textPane.getStyledDocument().setCharacterAttributes(0, textPane.getStyledDocument().getLength(), defaultStyle, true);
    }

    public static void main(String args[]) {                
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new DemoFrame().setVisible(true);
            }
        });
    }    
}

重现问题:

  1. 编译并运行上面的课程
  2. 尝试调整框架大小 - 自动换行功能
  3. 找到并删除我在下面复制的三行
  4. 按下Reset style按钮
  5. 关闭自动换行
  6. * Onpti edintsy amy ont vayr oto humc 
    ** Het angre fo the coall ption desitnsei of a igsenl pisnotte nutip ushold eb sallm. Ahtt is: teh orait of het oclla oitnp idsentise oarund any 2 ipnost lsdhou eb lmitied.
    ** Hte lcoal noipt deisynt ushlod otn ahencg sdduelyn (gliftyscaiinn ni a hotsr idnsteac). 
    

    编辑2

    使用荧光笔而不是样式解决了我的问题,但我仍然很好奇原始方法出了什么问题。

1 个答案:

答案 0 :(得分:0)

这看起来像我在这里问过的问题:Strange text wrapping with styled text in JTextPane with Java 7

据我所知,这是Java 7中的一个错误,Oracle Java Bug Parade中没有记录。我还没有找到解决方法(在我的情况下使用荧光笔不是一个选项)。