我有一个JLabel
我像这样填充它
String descriptionText = StringEscapeUtils.escapeHtml(rule.getDescription());
descriptionText = descriptionText.replaceAll("\n", "<br>");
descriptionLbl.setText(String.format("<html>%s</html>", descriptionText));
在这种情况下,如果 rule.getDescription()
返回类似于 "/* test */"
的内容,则最终结果是空的 JLabel
?为什么是这样?我认为 StringEscapeUtils#escapeHtml
会捕获所有转义字符。
最佳答案
这是一个较小的测试应用程序,显示了问题:
import javax.swing.JFrame;
import javax.swing.JLabel;
public class LabelTest {
public static void main(String args[]) {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel();
String text = "<html>/test</html>";
label.setText(text);
frame.add(label);
frame.setSize(500, 500);
frame.setVisible(true);
}
}
我发现的唯一解决办法是使用特殊的 html 代码:
String text = "<html>/test</html>";
您可以有一个使用replaceAll() 的处理方法来自动执行此过程。
我不确定为什么会发生这种情况,并且似乎不会发生任何其他特殊字符。奇怪。
关于Java JLabel,为什么 "<html>/* test */</html>"导致JLabel为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22971158/