如何在 Swing JOptionPane 中制作红色消息?
How to make a red message in Swing JOptionPane?
我想让我的错误消息变成红色,这是使用 Swing 制作的:
JOptionPane.showMessageDialog(null,
"Welcome\nTo\nJava\nProgramming!", "subject", JOptionPane.ERROR_MESSAGE);
但是这段代码会出现一个黑色对话框,请问有什么方法可以让它变成红色?
您可以在 HTML 的帮助下实现它,如下所示:
JOptionPane.showMessageDialog(null ,
"<html><div color=red>Welcome<br/>To<br/>Java<br/>Programming!" , "subject" , JOptionPane.ERROR_MESSAGE);
public void showColoredMessageDialog(String message, Color color){
//The label to show your message
JLabel l = new JLabel(message);
//the color for your message
l.setForeground(color);
//show JOptionPane.showMessageDialog with your custom color message
JOptionPane.showMessageDialog(this, l);
}
//You can call this method like for ex:
String msg = "hello world!";
//display this message with red color
showColoredMessageDialog(msg, Color.red);
//or you can also pass messages with variable values
int count = 10;
String msg2 = "the value of count is : " + count;
//display this message but this time with green color
showColoredMessageDialog(msg2, Color.green);
我想让我的错误消息变成红色,这是使用 Swing 制作的:
JOptionPane.showMessageDialog(null,
"Welcome\nTo\nJava\nProgramming!", "subject", JOptionPane.ERROR_MESSAGE);
但是这段代码会出现一个黑色对话框,请问有什么方法可以让它变成红色?
您可以在 HTML 的帮助下实现它,如下所示:
JOptionPane.showMessageDialog(null ,
"<html><div color=red>Welcome<br/>To<br/>Java<br/>Programming!" , "subject" , JOptionPane.ERROR_MESSAGE);
public void showColoredMessageDialog(String message, Color color){
//The label to show your message
JLabel l = new JLabel(message);
//the color for your message
l.setForeground(color);
//show JOptionPane.showMessageDialog with your custom color message
JOptionPane.showMessageDialog(this, l);
}
//You can call this method like for ex:
String msg = "hello world!";
//display this message with red color
showColoredMessageDialog(msg, Color.red);
//or you can also pass messages with variable values
int count = 10;
String msg2 = "the value of count is : " + count;
//display this message but this time with green color
showColoredMessageDialog(msg2, Color.green);