Multi-line tooltips in Java?

前端 未结 10 1608
故里飘歌
故里飘歌 2020-12-02 12:31

I\'m trying to display tooltips in Java which may or may not be paragraph-length. How can I word-wrap long tooltips?

10条回答
  •  感动是毒
    2020-12-02 13:23

    This could be improved somewhat, but my approach was a helper function called before setting tooltip that split the tooltip text at provided length, but adjusted to break words on space where possible.

    import java.util.ArrayList;
    import java.util.List;
    
    /**
     *
     */
    public class MultiLineTooltips
    {
        private static int DIALOG_TOOLTIP_MAX_SIZE = 75;
        private static final int SPACE_BUFFER = 10;
    
        public static String splitToolTip(String tip)
        {
            return splitToolTip(tip,DIALOG_TOOLTIP_MAX_SIZE);
        }
        public static String splitToolTip(String tip,int length)
        {
            if(tip.length()<=length + SPACE_BUFFER )
            {
                return tip;
            }
    
            List  parts = new ArrayList<>();
    
            int maxLength = 0;
            String overLong = tip.substring(0, length + SPACE_BUFFER);
            int lastSpace = overLong.lastIndexOf(' ');
            if(lastSpace >= length)
            {
                parts.add(tip.substring(0,lastSpace));
                maxLength = lastSpace;
            }
            else
            {
                parts.add(tip.substring(0,length));
                maxLength = length;
            }
    
            while(maxLength < tip.length())
            {
                if(maxLength + length < tip.length())
                {
                    parts.add(tip.substring(maxLength, maxLength + length));
                    maxLength+=maxLength+length;
                }
                else
                {
                    parts.add(tip.substring(maxLength));
                    break;
                }
            }
    
            StringBuilder  sb = new StringBuilder("");
            for(int i=0;i");
            }
            sb.append(parts.get(parts.size() - 1));
            sb.append((""));
            return sb.toString();
        }
    }
    

    Use like

    jComponent.setToolTipText(MultiLineTooltips.splitToolTip(TOOLTIP));
    

提交回复
热议问题