换行符属性JEditorPane

时间:2012-10-24 23:22:26

标签: java swing jeditorpane linewrap

有人知道如何更改JEditorPane的换行属性吗?

我无法在JTextPane文本中找到换行符(它既不是 \ n 也不是 \ r ),所以我无法计算这段文字的行数正确。我想更改 \ n 的换行符属性。

2 个答案:

答案 0 :(得分:3)

这个例子对我有用......

public class TestEditorPane {

    public static void main(String[] args) {
        new TestEditorPane();
    }

    public TestEditorPane() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new EditorPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class EditorPane extends JPanel {

        private JEditorPane editor;

        public EditorPane() {

            setLayout(new GridBagLayout());
            editor = new JEditorPane();
            editor.setContentType("text/plain");

            JButton button = new JButton("Dump");
            button.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String text = editor.getText();
                    String[] parts = text.split(System.getProperty("line.separator"));
//                    String[] parts = text.split("\n\r");
                    for (String part : parts) {
                        if (part.trim().length() > 0) {
                            System.out.println(part);
                        }
                    }
                }
            });

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.weightx = 1;
            gbc.weighty = 1;
            gbc.fill = GridBagConstraints.BOTH;
            add(editor, gbc);

            gbc.gridx = 0;
            gbc.gridy++;
            gbc.weightx = 0;
            gbc.weighty = 0;
            gbc.fill = GridBagConstraints.NONE;
            add(button, gbc);
        }
    }
}

在Windows下,换行符似乎是/n/r。我也使用了系统属性line.separator,它似乎对我有效。

答案 1 :(得分:3)

使用javax.swing.text.Utilities.getRowStart()/getRowEnd()计算行数。

实际上,当文本被包装时,不会插入char。请参阅http://java-sl.com/wrap.html以了解包装的工作原理。