格式化jdialog框中的文本

我有一个JOptionPane:

JOptionPane.showMessageDialog(null, text); 

文字是一个刺痛:

 String text = "Hello world." 

我想要做的是改变文本的颜色,特别是单个单词,让我们说’你好’。 所以我试过的是:

 String t1 = "Hello"; String t2 = "world." Font serifFont = new Font("Serif", Font.BOLD, 12); AttributedString as = new AttributedString(t1); as.addAttribute(TextAttribute.FONT, serifFont); as.addAttribute(TextAttribute.FOREGROUND, Color.red); JOptionPane.showMessageDialog(null, as+t2); 

我不熟悉attributiontext(),这不会工作。 它这样做:

“java.text.AttributedString@479c479cworld”

我缺少一步吗? 这不是正确的方法吗? 有什么建议么?

应该可以使用html来解决这个问题,即

 String t = "Hello world!"; 

有关详细信息,请参阅http://docs.oracle.com/javase/tutorial/uiswing/components/html.html 。

您可以在Message参数中将Component传递给JOptionPane,并使用它来显示您的消息。

JLabel或带有标签的JPanel

更新

JLabel,JPanel和HTML文本示例

 public class TestOptionPane { public static void main(String[] args) { JLabel label = new JLabel("Hello"); label.setForeground(Color.RED); JOptionPane.showMessageDialog(null, label); JPanel pnl = new JPanel(new GridBagLayout()); pnl.add(createLabel("The quick")); pnl.add(createLabel(" brown ", Color.ORANGE)); pnl.add(createLabel(" fox ")); JOptionPane.showMessageDialog(null, pnl); String text = "The Quick brown fox"; JOptionPane.showMessageDialog(null, text); } public static JLabel createLabel(String text) { return createLabel(text, UIManager.getColor("Label.foreground")); } public static JLabel createLabel(String text, Color color) { JLabel label = new JLabel(text); label.setForeground(color); return label; } } 

在Mac-

Mac上的JOptionPane示例

在Windows上 –

Windows上的JOptionPane示例