2012-01-30 213 views
10

我已经添加JOptionPane到我的应用程序,但我不知道如何将背景颜色更改为白色?如何更改JOptionPane的背景颜色?

`int option = JOptionPane.showConfirmDialog(bcfiDownloadPanel, 
      new Object[]{"Host: " + source, panel}, 
      "Authorization Required", 
      JOptionPane.OK_CANCEL_OPTION, 
      JOptionPane.PLAIN_MESSAGE 
    ); 

    if (option == JOptionPane.OK_OPTION) {     }` 

回答

14

通过使用UIManager

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

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

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

+1为简单的方式 – mKorbel 2012-01-30 14:08:41

+5

请注意,这将改变所有实例的背景。 – mre 2012-01-30 14:14:28

+0

是否可以将我的自定义按钮添加到它? – itro 2012-01-30 16:01:02

1

使用这样的事情来改变背景颜色只为这一个消息显示,而不是整个系统...

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

什么是“messageBox()”方法? – 2016-02-28 13:57:31

3

JOptionPane image

对于任何有图像问题的人,我找到/改编了一个解决方案。在我的系统中,我得到了这个结果,无论我是否使用其他人发布的UIManager解决方案,或者制作了一个JDialog并使用了jd.getContentPane()。setBackground(Color.white)。因此,这里的工作围绕我来到了,在这里你循环递归穿过的JOptionPane的每个组件,并设置每个JPanel的背景色:

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

在你的代码,你想有消息弹出,沿着线的东西:

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

JOptionPane paneJDialog jd先前所建立的。希望这有助于任何有此问题的人。

+0

非常感谢你 – 2017-08-01 00:01:47

+0

这是最好的回应 – 2017-08-01 00:02:09

0

如果您遇到与erik k atwood相同的问题,请使用此代码。这就解决了这个问题:

UIManager.put("OptionPane.background", Color.WHITE); 
UIManager.getLookAndFeelDefaults().put("Panel.background", Color.WHITE);