How to change background color of JOptionPane?

不想你离开。 提交于 2019-11-28 08:31:42

By using the UIManager class

 import javax.swing.UIManager;

 UIManager UI=new UIManager();
 UI.put("OptionPane.background",new ColorUIResource(255,0,0));
 UI.put("Panel.background",new ColorUIResource(255,0,0));

or

 UIManager UI=new UIManager();
 UI.put("OptionPane.background", Color.white);
 UI.put("Panel.background", Color.white);

 JOptionPane.showMessageDialog(null,"Text","SetColor",JOptionPane.INFORMATION_MESSAGE);

JOptionPane image

For anyone having the problem in the image, I found/adapted a solution. On my system, I got that result, whether I used the UIManager solution as others have posted, or made a JDialog and used jd.getContentPane().setBackground(Color.white). So here is the work-around I came up with, where you loop recursively through each component in the JOptionPane, and set each JPanel's background color:

private void getComponents(Container c){

    Component[] m = c.getComponents();

    for(int i = 0; i < m.length; i++){

        if(m[i].getClass().getName() == "javax.swing.JPanel")
            m[i].setBackground(Color.white);

        if(c.getClass().isInstance(m[i]));
            getComponents((Container)m[i]);
    }
}

In your code where you want to have the message pop-up, something along the lines of:

pane = new JOptionPane("Your message here", 
                JOptionPane.PLAIN_MESSAGE ,JOptionPane.DEFAULT_OPTION);
        getComponents(pane);
        pane.setBackground(Color.white);
        jd = pane.createDialog(this, "Message");
        jd.setVisible(true);

Where JOptionPane pane and JDialog jd have previously been created. Hope this helps anyone who had that issue.

Use something like this to change the background color just for this one message display and not the whole system...

    Object paneBG = UIManager.get("OptionPane.background");
    Object panelBG = UIManager.get("Panel.background");
    UIManager.put("OptionPane.background", new Color(...));
    UIManager.put("Panel.background", new Color(...));

    int ret = messageBox(msg, null, (short)type);

    UIManager.put("OptionPane.background", paneBG);
    UIManager.put("Panel.background", panelBG);

Use this code if you have the same problem as erik k atwood. This solves the problem:

UIManager.put("OptionPane.background", Color.WHITE);
UIManager.getLookAndFeelDefaults().put("Panel.background", Color.WHITE);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!