首页 > 解决方案 > 如何删除最后一行/组件/图标/小部件/等。来自 JTextPane

问题描述

我有一个庞大的 Java 项目,它使用像 UI 这样的控制台。对于控制台,我使用 JTextPane。最近我需要分别删除第一行和最后一行的方法。我删除第一行的方法非常简单,如下

public void removeFirstLine() {
        try {
            Element root = outputArea.getDocument().getDefaultRootElement();
            Element first = root.getElement(0);
            outputArea.getDocument().remove(first.getStartOffset(), first.getEndOffset());
            outputArea.setCaretPosition(outputArea.getDocument().getLength());
        } catch (BadLocationException e) {
            ErrorHandler.handle(e);
        }
    }

然而,当我尝试删除最后一行时,我的问题出现了(不是文本,我重复不是文本)。此行可以是任何可附加到 JTextPane 的内容,例如自定义组件、文本字符串、图标等。如果有人知道如何删除附加到 JTextPane 的最后一个“东西”,我将不胜感激。

编辑:添加最小的可重现示例:

import javax.swing.*;
import javax.swing.text.*;

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

    private static final String ELEM = AbstractDocument.ElementNameAttribute;
    private static final String ICON = StyleConstants.IconElementName;
    private static final String COMP = StyleConstants.ComponentElementName;
    private JTextPane outputArea;

    Test() {
        try {
            //init pane
            outputArea = new JTextPane();

            //insert component
            JTextField c = new JTextField(20);
            Style cs = outputArea.getStyledDocument().addStyle("name", null);
            StyleConstants.setComponent(cs, c);
            outputArea.getStyledDocument().insertString(outputArea.getStyledDocument().getLength(), "string", cs);

            //new line
            println("");

            //add string
            println("this is a string added to the pane");

            //add image
            outputArea.insertIcon(new ImageIcon("/path/to/image.png"));

            //new line
            println("");

            //before
            printContents();

            //----------------------------
            //call removeLastLine() as many times as needed and it should remove the last added "thing"
            //regardless of the order added (ex: component, text, icon should function the same as text, text, text, component obviously)

            //changes should be reflected here
            printContents();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void removeLastLine() {
        //TODO remove last line of text, last component, last image icon, etc.
    }

    public void println(String Usage) {
        try {
            StyledDocument document = (StyledDocument) outputArea.getDocument();
            document.insertString(document.getLength(), Usage + "\n", null);
            outputArea.setCaretPosition(outputArea.getDocument().getLength());
        }

        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void printContents() {
        try {
            ElementIterator iterator = new ElementIterator(outputArea.getStyledDocument());
            Element element;
            while ((element = iterator.next()) != null) {
                System.out.println(element);
                AttributeSet as = element.getAttributes();
                if (as.containsAttribute(ELEM, ICON)) {
                    System.out.println(StyleConstants.getIcon(as).getClass());
                }
                else if (as.containsAttribute(ELEM, COMP)) {
                    System.out.println(StyleConstants.getComponent(as).getClass());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

标签: javaswingjtextpane

解决方案


以下是我之前使用的代码,用于删除文本:

public void removeLastLine() {
    //  We use start minus 1 to make sure we remove the newline
    //  character of the previous line
    Element root = outputArea.getDocument().getDefaultRootElement();
    Element line = root.getElement(root.getElementCount() - 1);
    int start = line.getStartOffset();
    int end = line.getEndOffset();

    try
    {
        outputArea.getDocument().remove(start - 1, end - start);
    }
    catch(BadLocationException ble)
    {
        System.out.println(ble);
    }
}

似乎也适用于其他对象,因为“之后”输出与“之前”输出不同。

我将让您验证文本窗格是否按预期更新。

我从文档中的限制线中获取了代码

编辑:

上面的代码在尝试删除第一行时不起作用,因为起始偏移量将为负数。

以下是还处理删除第一行的更新版本:

import java.awt.*;
import javax.swing.*;
import javax.swing.*;
import javax.swing.text.*;

public class Test {
    public static void main(String[] args) {

        new Test();
    }

    private static final String ELEM = AbstractDocument.ElementNameAttribute;
    private static final String ICON = StyleConstants.IconElementName;
    private static final String COMP = StyleConstants.ComponentElementName;
    private JTextPane outputArea;

    Test() {
        try {
            //init pane
            outputArea = new JTextPane();

            JButton button = new JButton("Remove Last Line");
            button.addActionListener((e) -> removeLastLine());

            JFrame frame = new JFrame();
            frame.add( new JScrollPane(outputArea) );
            frame.add( button, BorderLayout.PAGE_END);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.setSize(300, 300);
            frame.setLocationByPlatform( true );
            frame.setVisible( true );

            println("first line");

            //insert component
            JTextField c = new JTextField(20);
            Style cs = outputArea.getStyledDocument().addStyle("name", null);
            StyleConstants.setComponent(cs, c);
            outputArea.getStyledDocument().insertString(outputArea.getStyledDocument().getLength(), "string", cs);

            //new line
            println("");

            //add string
            println("this is a string added to the pane");

            //add image
            outputArea.insertIcon(new ImageIcon("about16.gif"));

            //new line
            println("\nsecond last line");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void removeLastLine()
    {
        //  We use start minus 1 to make sure we remove the newline
        //  character of the previous line

        Element root = outputArea.getDocument().getDefaultRootElement();
        Element line = root.getElement(root.getElementCount() - 1);
        int start = line.getStartOffset();
        int end = line.getEndOffset();

        try
        {
            int offset = start - 1;
            int length = end - start;

            //  removing the first line

            if (offset < 0)
            {
                offset = 0;
                length -= 1;
            }

            outputArea.getDocument().remove(offset, length);
        }
        catch(BadLocationException ble)
        {
            System.out.println(ble);
        }
    }

    public void println(String Usage) {
        try {
            StyledDocument document = (StyledDocument) outputArea.getDocument();
            document.insertString(document.getLength(), Usage + "\n", null);
            outputArea.setCaretPosition(outputArea.getDocument().getLength());
        }

        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

推荐阅读