如何将 JButton 中的 html 文本移至左侧?

发布于 2024-08-30 08:36:19 字数 307 浏览 4 评论 0原文

我使用 HTML 将文本放入 JButton 中。通过这种方式,我可以调整颜色和文本大小。我不喜欢的是按钮左边框和文本的距离(这个间隔太大)。有没有办法缩短这个距离?我认为它应该是 HTML 代码的 style 中的某个参数。

代码示例:

JButton btn = new JButton("<html><span style='color:#000000; font-size: 11pt;'>" + label + "</span></html>");

I use HTML to put text into a JButton. In this way I can play with colors and text size. What I do not like is the distance from the left border of the button and the text (this separation is too large). Is there a way to decrease this distance? I think it should be some parameter in the style of the HTML code.

Sample of the code:

JButton btn = new JButton("<html><span style='color:#000000; font-size: 11pt;'>" + label + "</span></html>");

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

舞袖。长 2024-09-06 08:36:19

我建议以编程方式执行此操作,而不是尝试使用 HTML 执行此操作,因为您更有可能看到跨平台的一致结果。

JButton btn = ...
btn.setHorizontalTextPosition(SwingConstants.LEFT);

然后,您可以通过重写paintComponent(更多工作)或在启动时修改FontUIResource对象来自定义字体大小(尽管这会影响所有按钮的字体大小);例如

FontUIResource f = new FontUIResource("Tahoma", Font.PLAIN, 11);
Enumeration<Object> it = UIManager.getDefaults().keys();

while (it.hasMoreElements()) {
    Object key = it.nextElement();
    if (UIManager.get(key) instanceof FontUIResource) {
        UIManager.put(key, f);
    }
}

I would recommend doing this programmatically rather than attempting to do it with HTML as you'll be more likely to see consistent results across platforms.

JButton btn = ...
btn.setHorizontalTextPosition(SwingConstants.LEFT);

Then you can customise the font size by either overriding paintComponent (more work) or modifying the FontUIResource object at start-up (although this will affect the font size of all buttons); e.g.

FontUIResource f = new FontUIResource("Tahoma", Font.PLAIN, 11);
Enumeration<Object> it = UIManager.getDefaults().keys();

while (it.hasMoreElements()) {
    Object key = it.nextElement();
    if (UIManager.get(key) instanceof FontUIResource) {
        UIManager.put(key, f);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文