如何在Swing JOptionPane中发出红色消息?

时间:2015-03-17 12:17:28

标签: java swing joptionpane

我想让我的错误消息变为红色,这是使用Swing制作的:

JOptionPane.showMessageDialog(null,
 "Welcome\nTo\nJava\nProgramming!", "subject", JOptionPane.ERROR_MESSAGE);

但是这段代码会显示一个带有黑色消息的对话框,是什么方法让它成为红色?

2 个答案:

答案 0 :(得分:5)

您可以通过下一步的HTML帮助实现它:

JOptionPane.showMessageDialog(null ,
     "<html><div color=red>Welcome<br/>To<br/>Java<br/>Programming!" , "subject" , JOptionPane.ERROR_MESSAGE);

Red multi-line text in option pane

答案 1 :(得分:0)

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