2012-01-30 223 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);