2012-08-17 57 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