How to make an overflowed TextArea truncate text and show ellipsis in the end?

♀尐吖头ヾ 提交于 2019-12-24 08:39:06

问题


I know this seems to be a stupid question, but so far all the answers I found ask me to use html tags. Is there a easier way to do it? The TextArea may change size.


回答1:


Override the insertString method of the Document, so that whenever a string is inserted, the extra characters are removed and an ellipsis is inserted. Here is an example:

JTextArea area = new JTextArea();
area.setDocument(new PlainDocument() {
    private static final long serialVersionUID = 1L;
    private static final int MAX = 100;

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        super.insertString(offs, str, a);

        //has the length been exceeded
        if(getLength() > MAX) {

            //remove the extra characters.
            //need to take into account the ellipsis, which is three characters.
            super.remove(MAX - 3, getLength() - MAX + 3);

            //insert ellipsis
            super.insertString(getLength(), "...", a);
        }
    } 
});



回答2:


The proper way to do this is to create a custom View that paints an ellipsis when required. But since I have no idea how to do this I'll try a little hack you might be able to use:

// This comment is here so that the text will wrap to the next line and you should see the ellipsis,
// indicating that there is more text.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;

class TextAreaEllipsis
{
    public static void main(String a[])
    {
        JTextArea textArea = new JTextArea(4, 15)
        {
            protected void paintComponent(Graphics g)
            {
                super.paintComponent(g);

                int preferredHeight = (int)getUI().getRootView(this).getPreferredSpan(View.Y_AXIS);

                if (preferredHeight > getSize().height)
                    paintEllipsis(g);
            }

            private void paintEllipsis(Graphics g)
            {
                try
                {
                    int caretWidth = 1;
                    FontMetrics fm = getFontMetrics( getFont() );
                    String ellipsis = "...";
                    int ellipsisWidth = fm.stringWidth( ellipsis ) + caretWidth;

                    Insets insets = getInsets();
                    int lineWidth = getSize().width - insets.right;
                    Point p = new Point(lineWidth, getSize().height - 1);

                    int end = viewToModel( p );
                    Rectangle endRectangle = modelToView( end );
                    int start = end;
                    Rectangle startRectangle = endRectangle;
                    int maxWidth = lineWidth - ellipsisWidth;

                    while (startRectangle.x + startRectangle.width > maxWidth)
                    {
                        startRectangle = modelToView( --start );

                    }

                    Rectangle union = startRectangle.union( endRectangle );
                    g.setColor( getBackground() );
                    g.fillRect(union.x + caretWidth, union.y, union.width, union.height);
                    g.setColor( getForeground() );
                    g.drawString("...", union.x + caretWidth, union.y + union.height - fm.getDescent());
                }
                catch(BadLocationException ble)
                {
                    System.out.println( ble );
                }
            }
        };

        textArea.setLineWrap( true );
        textArea.setWrapStyleWord( true );
        textArea.setPreferredSize( textArea.getPreferredScrollableViewportSize() );

        try
        {
            FileReader reader = new FileReader( "TextAreaEllipsis.java" );
            BufferedReader br = new BufferedReader(reader);
            textArea.read( br, null );
            br.close();
        }
            catch(Exception e2) { System.out.println(e2); }

        JFrame frame = new JFrame("TextArea Ellipsis");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(textArea);
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}


来源:https://stackoverflow.com/questions/6747156/how-to-make-an-overflowed-textarea-truncate-text-and-show-ellipsis-in-the-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!