gpt4 book ai didi

java - 有没有办法在 JLabel 中打印 AttributedString?

转载 作者:行者123 更新时间:2023-12-01 04:46:25 25 4
gpt4 key购买 nike

我有一个带有常规文本和一些下标的AttributedString。我想将文本放入 JLabel 中而不丢失格式。

这可能吗?如果没有,最好的选择是什么?

编辑:这是一些示例代码来进一步解释我的问题:

import javax.swing.JLabel;
import javax.swing.JFrame;
import java.text.AttributedString;
import java.awt.font.TextAttribute;
public class LabelExample extends JFrame implements Runnable
{
private JLabel label;
private AttributedString as;
public LabelExample()
{
as = new AttributedString("Ten to the fifth is 105");
as.addAttribute(TextAttribute.SUPERSCRIPT, TextAttribute.SUPERSCRIPT_SUPER, 22, 23);
label = new JLabel(as);
//the above line doesn't accept AttributedString
//as a suitable constructor
this.add(label);
}
public void run()
{
setSize(500, 500);
setVisible(true);
}
public static void main(String[] args)
{
LabelExample e = new LabelExample();
javax.swing.SwingUtilities.invokeLater(e);
}
}

最佳答案

通过覆盖 JLabel 使其行为类似于 JPanelJComponent 并使用其 paint 方法。这显然不是一个好主意,直​​接使用 JPanel 即可。 Graphics2D 上下文知道如何处理 AttributedString(具体来说是字符迭代器)。

JLabel 直接了解 HTML 渲染,也许这可以帮助您完成特定任务,因为您可以轻松构建带有上标标签的 HTML 字符串。我不知道将 AttributedString 转换为 HTML 的舒适方法。

关于java - 有没有办法在 JLabel 中打印 AttributedString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15778329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com