Python中文网

一个关于 编程问题的解答网站.

有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在Swing JOptionPane中生成红色消息?

我想使我的错误消息变成红色,这是使用Swing生成的:

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

但是这段代码会显示一个带有黑色消息的对话框,如何将其变为红色


共 (2) 个答案

  1. # 1 楼答案

    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);
    
  2. # 2 楼答案

    您可以借助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