如何在Java中以粗体显示的消息框中创建特定单词(变量)?

时间:2010-03-14 02:23:33

标签: java messagebox text-formatting

我正在尝试在我的Java程序中将消息框中的一个单词(变量)加粗。这是我的代码:

int n = messageBox.showConfirmDialog(frame,
"The File "+ file +" already exists." +
"\n" + "Do you want to replace it?",
"File Already Exists!",
messageBox.YES_NO_OPTION);

我想让变量“file”在我的消息框中以粗体显示。到目前为止,我只能将整个消息框以粗体显示,或者根本不显示。我该怎么做?

2 个答案:

答案 0 :(得分:3)

使用HTML对我来说很好。问题是默认字体已经是粗体,因此您看不到其他字体。

尝试使用“斜体”标签或“font”标签,并指定不同的颜色以查看差异。

或者,您可以使用自定义字体传入自己的JLabel,而不是传入文本字符串。类似的东西:

String message = "<html>The File <b> file </b> already exists</html>";
JLabel label = new JLabel(message);
label.setFont( UIManager.getFont("TextField.font") );

int result = JOptionPane.showConfirmDialog(
    this,
    label,
    "File already exists!",
    JOptionPane.YES_NO_OPTION);

答案 1 :(得分:2)

尝试在html标记中包装文本。许多swing组件支持一些基本的HTML,如斜体,粗体和下划线。例如,您应该将代码更改为:

int n = messageBox.showConfirmDialog(frame,
"<html>The File <b>"+ file +"</b> already exists." +
"\n" + "Do you want to replace it?</html>",
"File Already Exists!",
messageBox.YES_NO_OPTION);