2012-08-17 63 views
0

格式化文本我有一个的JOptionPane:中的JDialog框

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); 

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

[email protected]

是否有步骤我失踪?这不正确吗?有什么建议么?

+0

为了更快提供更好的帮助,请发布[SSCCE](http://sscce.org/)。 – 2012-08-17 20:51:24

回答

5

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

String t = "<html><font color=#ffffdd>Hello</font> world!"; 

更多信息,请参见http://docs.oracle.com/javase/tutorial/uiswing/components/html.html

+0

这似乎并没有为我工作,仍具有在该对话框文本HTML标记。 – whitewolfpgh 2012-08-17 16:07:07

+0

我可能没有这样做,所以请你详细说明。如果这句话是:快速的棕色狐狸,该怎么办? 而我只想要“棕色”是棕色? – whitewolfpgh 2012-08-17 16:18:06

+0

试过没有用,我知道十六进制不是用于布朗没有时间查看它: String text =“快速棕色狐狸。” – whitewolfpgh 2012-08-17 16:25:23

3

您可以通过一个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 = "<html>The Quick <span style='color:green'>brown</span> fox</html>"; 
     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的

JOptionPane Example on Mac

在Windows上 -

JOptionPane example on Windows

+0

这似乎并没有任何工作,JOptionPane.showmessagedialog()似乎做一个toString方法来传递任何东西到文本字段。所以它实际上显示了组件的属性而不是组件本身。 – whitewolfpgh 2012-08-17 16:16:42

+0

真的,为我工作,可能只采取JLabel – MadProgrammer 2012-08-17 20:59:20

+0

@whitewolfpgh我回去并扩大了我的测试代码,这一切似乎都适合我... – MadProgrammer 2012-08-17 21:51:46