Java Swing中的自动换行具有硬换行像素限制

时间:2018-09-16 04:20:34

标签: java swing limit stringbuilder word-wrap

在摆动环境中用Java实现自动换行时遇到问题。我在像素上有一个严格的限制,无法逾越。我觉得自己已经接近了,因为我找到了一个可以包装的解决方案,但是它可以让最后一个单词超出限制,然后再转到下一行。

  

'ni'是一个全部被绘制到的缓冲图像。

     

“ theSettings”自定义类,其中包含文本变量。

     

'theText'是需要包装的字符串。

这就是传递给方法的内容:

FontMetrics fm = ni.createGraphics().getFontMetrics(theSettings.getFont());
//Get pixel width of string and divide by # of characters in string to get estimated width of 1 character
int charPixelWidth = fm.stringWidth(theText) / theText.length();
int charWrap = theSettings.getPixelsTillWrap() / charPixelWidth;
List<String> textList = testWordWrap(theText, charWrap);

我正在使用此方法进行测试:

//Custom String Wrapper as StringUtils.wrap keeps cutting words in half
public static List<String> testWordWrap(String wrapMe, int wrapInChar) {
    StringBuilder sb = new StringBuilder(wrapMe);

    int count = 0;
    while((count = sb.indexOf(" ", count + wrapInChar)) != -1) {
        sb.replace(count, count + 1, "\n");
    }

    String toArray = sb.toString();
    String[] returnArray = toArray.split("\\n");

    ArrayList<String> returnList = new ArrayList<String>();
    for(String s : returnArray) {
        returnList.add(s);
    }

    return returnList;
}

使用示例: enter image description here enter image description here

我也在文本中间替换了图像,但是图像的大小恰好是要替换的文本的大小;所以这不应该是一个问题。蓝线是边界框,显示包装应在何处结束。它显示文本继续绘制。我需要将“成功”包装到下一行的函数;因为包装纸在任何情况下都不会溢出。

编辑:图像的数组以.toString();

运行

[分辨率:+ | FT |如果成功,并且匹配了| EA |]

[任何:+ | MT |当您获得任意数量的| QT |]

1 个答案:

答案 0 :(得分:0)

我能够找到答案。我将字符串分割成空格,然后尝试一次将每个单词加一个。如果太长,请跳至下一行。在这里,它已过注释以帮助其他任何人解决同样的问题。干杯!

//@Author Hawox
//split string at spaces
//for loop checking to see if adding that next word moves it over the limit, if so go to next line; repeat
public static List<String> wordWrapCustom(String wrapMe, FontMetrics fm, int wrapInPixels){
    //Cut the string into bits at the spaces
    String[] split = wrapMe.split(" ");

    ArrayList<String> lines = new ArrayList<String>(); //we will return this, each item is a line
    String currentLine = ""; //All contents of the currentline

    for(String s : split) {
        //Try to add the next string
        if( fm.stringWidth(currentLine + " " + s) >= wrapInPixels ) {
            //Too big
            if(currentLine != "") { //If it is still bigger with an empty string, still add at least 1 word
                lines.add(currentLine); //Add the line without this string 
                currentLine = s; //Start next line with this string in it
                continue;
            }
        }
        //Still have room, or a single word that is too big
        //add a space if not the first word
        if(currentLine != "")
            currentLine = currentLine + " ";

        //Append string to line
        currentLine = currentLine + s;
    }
    //The last line still may need to get added
    if(currentLine != "") //<- Should not get called, but just in case
        lines.add(currentLine);

    return lines;
}