【问题标题】:Swing Dialogbox html formatting 'cutting off' half of the contentSwing Dialogbox html格式化'切断'一半内容
【发布时间】:2016-05-24 14:13:21
【问题描述】:

我有一个对话框,我希望将特定部分设为粗体。 我知道我必须使用html 执行此操作,但是执行此操作时我似乎丢失了一半的对话消息。

原文(无粗体):

public class View extends JFrame {
    private final static String NEW_LINE = System
            .getProperty("line.separator");
    public void someMethodDisplayDialog(String string1, String string2, String string3) {
        JOptionPane.showMessageDialog(this,
                "An problem occured: " + string1
                        + NEW_LINE 
                        + string2 + " Error: "
                        + string3,
                "Error",
                JOptionPane.ERROR_MESSAGE);
    }
}

让我们说:

  • string1 = "Wrong Key!",
  • string2 = "Input",
  • string = "Z key pressed"

在对话框中显示:


出现问题:错误的密钥!
输入错误:按下 Z 键
我想加粗“输入错误:”部分。我有这个代码:
        JOptionPane.showMessageDialog(this,
                "An problem occured: " + string1
                        + NEW_LINE + "<html><b>" 
                        + string2 + " Error:</b></html> "
                        + string3,
                "Error",
                JOptionPane.ERROR_MESSAGE);

运行时,这会加粗我想要的内容,但 '切断' 其余部分,例如。 string3 不显示。
我尝试将结束的&lt;/b&gt;&lt;/html&gt; 标签放在string3 之后。
一切都显示了,但string3也是粗体,我不想要!

我在这里遗漏了一些明显的东西吗?我不确定为什么会这样?

【问题讨论】:

  • 1) 该字符串不会触发 HTML 格式化,因为 &lt;html&gt; 部分必须是字符串的第一部分。2) 为了尽快获得更好的帮助,请发布 minimal reproducible example 或 @987654322 @.

标签: java html swing jlabel joptionpane


【解决方案1】:

正如@Andrew Thompson 所说,您的消息必须&lt;html&gt; 标签开头。所以你的代码应该是这样的:

        JOptionPane.showMessageDialog(this,
            "<html>An problem occured: " + string1
                    + "<br><b>" 
                    + string2 + " Error:</b> "
                    + string3 + "</html>",
            "Error",
            JOptionPane.ERROR_MESSAGE);

【讨论】:

  • 使用 html 标签是否被认为是更好的做法,例如。 &lt;br&gt; 代替 Java 平台相关的换行符(System.getProperty("line.separator");System.lineSeperator();),如果在字符串中使用了 html?例如,如果我有上面的内容,但将 &lt;/html&gt; 移动到最后一行,因此最后一行显示为:+ string3 + "&lt;/html&gt;",则得到相同的结果。
  • 我想这个问题更像是在问,如果html在字符串中的某处使用,整个字符串是否应该被处理为html
  • 快乐的 4K(我不是让你超越极限的人)!赚了.. :) @Dan No. ;)
  • @AndrewThompson 谢谢。您已经在评论中回答了这个问题。我已经简单地解释了你的答案。
【解决方案2】:

在 string3 之后添加一个 + 号 编辑:您的 /html 标签正在切断字符串 3

JOptionPane.showMessageDialog(this,
                "An problem occured: " + string1
                        + NEW_LINE + "<html><b>" 
                        + string2 + " Error:</b>"
                        + string3 + "Error:</html>",
                JOptionPane.ERROR_MESSAGE);

【讨论】:

    猜你喜欢
    • 2013-09-29
    • 2014-08-29
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 2012-10-20
    • 2021-05-20
    相关资源
    最近更新 更多