【问题标题】:Wrap dynamic text automatically in Jbutton在 Jbutton 中自动换行动态文本
【发布时间】:2015-09-16 08:37:57
【问题描述】:

我的 Jbutton 有问题。

在我的应用程序中,您可以轻松更改 ui 语言,并且可以轻松覆盖按钮的默认翻译。

在这种情况下,一个按钮中的文本可以有多长是很不清楚的,但是我的按钮有一个固定的大小(因为图形和谐等等)。

现在我的问题是,我还没有找到用内部按钮边距包装文本的解决方案。

例子:

按钮 1: “你好” -> Hello 足够短,可以在没有换行符的情况下打印。

按钮 2: “大家好” -> 由于 html 标签,Hello guy 会自动换成两行。

按钮 3: “你好。” - >你好克。正好填充按钮的宽度。 HTML 没有自动换行!

现在,按钮 3 本身看起来很糟糕而且超载。

因此,我需要一个解决方案来自动换行比按钮宽或等于 -4px 的文本。

另外,不包含空格的文本,如果太长也应该换行。

【问题讨论】:

  • "在这种情况下,一个按钮中的文本可以有多长是很不清楚的,但是我的按钮是固定大小的(因为图形和谐等等)。" i> 为 GUI 的该部分使用GridLayout。它旨在计算显示最大所需的空间,然后在所有其他组件上强制执行该大小。更一般地,请参阅 Is there a “word wrap” property for JLabel?(同样适用于任何 HTML 感知 JComponent)。

标签: java swing user-interface jbutton word-wrap


【解决方案1】:

这个问题的一个非常简单的解决方案是实用方法,我写道。

只需在调用 super.paint(c,g); 之前在 *ButtonUI #paint 方法中调用它;

例如:

if (c instanceof AbstractButton) {
    String txt = button.getText();
    button.setText(getWrappedText(g, button, txt));
}

这是我免费使用的格式化程序(也用于优化;))

private static final String STR_NEWLINE = "<br />";
private FontRenderContext fontRenderContext = new FontRenderContext(new AffineTransform(), true, true);

private String getWrappedText(Graphics graphics, AbstractButton button, String str) {
    if( str != null ) {
        String text = str.replaceAll("<html><center>", "").replaceAll("</center></html>", "");
        int width = button.getWidth();
        Rectangle2D stringBounds = button.getFont().getStringBounds(text, fontRenderContext);
        if ( !str.contains(STR_NEWLINE) && (width-5) < ((Double)stringBounds.getWidth()).intValue()) {
            String newStr;
            if( str.contains(" ") ) {
                int lastIndex = str.lastIndexOf(" ");
                newStr = str.substring(0, lastIndex)+STR_NEWLINE+str.substring(lastIndex);
            } else {
                int strLength = ((str.length()/3)*2);
                newStr = str.substring(0, strLength)+STR_NEWLINE+str.substring(strLength);
            }
            return newStr;
        }
    }
    return str;
}

【讨论】:

    猜你喜欢
    • 2018-04-26
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多