JButtons 中的自动换行 [英] Word Wrap in JButtons

查看:55
本文介绍了JButtons 中的自动换行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 JButtons 中实现文本自动换行?我在运行时创建的动态按钮很少.我想在按钮上放置自动换行功能,以便我可以对按钮进行更好的测试.可以这样做吗?

Is it possible to achieve automatic word wrap of texts in JButtons? I am having few dynamic buttons which I create on runtime. I want to put word wrap feature on the buttons so that I can see some better test on buttons. Is it possible to do that?

推荐答案

此示例使用 Java 的内置 CSS 呈现功能来执行确定何时进行换行的繁重工作".它使用 JLabel,但同样的原则适用于任何渲染 HTML 的组件.

This example uses Java's inbuilt CSS rendering abilities to to do the 'heavy lifting' of determining when to do a line break. It uses a JLabel, but the same principles apply to any component that will render HTML.

import javax.swing.*;

class FixedWidthText {

    public static void showLabel(int width, String units) {
        String content1 = "<html>"
                + "<body style='background-color: white; width: ";
        String content2 = "'>"
                + "<h1>Fixed Width</h1>"
                + "<p>Body width fixed at ";
        String content3
                = " using CSS.  "
                + "Java's HTML"
                + " support includes support"
                + " for basic CSS.</p>";
        final String content = content1 + width + units
                + content2 + width + units + content3;
        Runnable r = () -> {
            JLabel label = new JLabel(content);
            JOptionPane.showMessageDialog(null, label);
        };
        SwingUtilities.invokeLater(r);
    }

    public static void main(String[] args) {
        showLabel(160, "px");
        showLabel(200, "px");
        showLabel(50, "%");
    }
}

屏幕截图

160 像素

这篇关于JButtons 中的自动换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆