whi*_*pgh 0 java fonts awt colors
我有一个JOptionPane:
JOptionPane.showMessageDialog(null, text);
Run Code Online (Sandbox Code Playgroud)
文字是一个刺痛:
String text = "Hello world."
Run Code Online (Sandbox Code Playgroud)
我想要做的是改变文本的颜色,特别是单个单词,让我们说'你好'.所以我试过的是:
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);
Run Code Online (Sandbox Code Playgroud)
我不熟悉attributiontext(),这不会工作.它这样做:
"java.text.AttributedString@479c479cworld"
我缺少一步吗?这不是正确的方法吗?有什么建议?
小智 6
应该可以使用html来解决这个问题,即
String t = "<html><font color=#ffffdd>Hello</font> world!";
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅http://docs.oracle.com/javase/tutorial/uiswing/components/html.html.
您可以Component
在 message 参数中将a 传递给 JOptionPane 并使用它来显示您的消息。
像 aJLabel
或 a 之类的东西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;
}
}
Run Code Online (Sandbox Code Playgroud)
在 Mac 上——
在 Windows 上 -