【问题标题】:How to make a red message in Swing JOptionPane?如何在 Swing JOptionPane 中发出红色消息?
【发布时间】:2015-03-17 12:17:28
【问题描述】:

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

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

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

【问题讨论】:

  • 在所以你可以找到this希望它对你有帮助
  • 哎呀,大红色图标足够对你来说不是红色的吗?值得注意的是,这偏离了平台默认的错误(通常),这很少是一件好事。

标签: java swing joptionpane


【解决方案1】:

你可以在 HTML 的帮助下实现它,如下所示:

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

【讨论】:

  • 但是如果我没有确切的变量并且它只是一个 var 怎么办,我的意思是当它像:String msg = "hello world",我怎样才能让 msg 变成红色,因为当我在上面的 html 代码中使用它,会显示 msg 而不是 hello world。
  • 你可以使用"
    "+msg
【解决方案2】:
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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    相关资源
    最近更新 更多