2010-03-18 82 views
1

我正在尋找一種禁用JPanel的好方法。我爲Java Swing GUI使用MVC設計。我希望在模型處理內容時禁用JPanel。我試過setEnabled(false)。這會禁用JPanel上的用戶輸入,但我希望它變灰以添加更多視覺效果。禁用具有視覺效果的JPanel

在此先感謝!

回答

2

你看過Glass Panes嗎?它們對已經包含組件的區域進行繪畫很有用。 Take a look

1

JPanel在禁用時不會出現任何不同,您必須重寫paintComponent()方法,以便在禁用時以不同的方式繪製它(或使用不同的顏色)。 像這樣的東西可能會奏效:

protected void paintComponent(Graphics g) { 
    if (this.isOpaque()) { 
     Color color = (this.isEnabled()) ? this.getBackground() : this.getBackground().brighter(); 
     g.setColor(color); 
     g.fillRect(0, 0, this.getWidth(), this.getHeight()); 
    } 
} 
+0

+1,除了你可能只需要調用的setBackground(彩色)。 – Chris 2010-03-18 16:39:27

0

由於要應用的視覺效果的最好使用玻璃面板。檢查this articleSwingX已經提供了您需要的組件以及更多。查看網站上提供的各種組件的演示。

0

另一個解決方案是使用JXLayer框架。玻璃窗格更靈活。看看該項目和this文章

1

禁用JPanel默認情況下不會禁用其子組件,只是阻止面板。解決方案,我建議是創建一個JPanel子類並覆蓋setEnabled方法是這樣的:

class JDisablingPanel extends JPanel { 
    @Override 
    public void setEnabled(boolean enabled) { 
     super.setEnabled(enabled); 
     this.setEnabledRecursive(this, enabled); 
    } 

    protected void setEnabledRecursive(Component component, boolean enabled) { 
     if (component instanceof Container) { 
      for (Component child : ((Container) component).getComponents()) { 
       child.setEnabled(enabled); 

       if (!(child instanceof JDisablingPanel)) { 
        setEnabledRecursive(child, enabled); 
       } 
      } 
     } 
    } 
}