开发者

Disable JPanel with visual effect

I'm looking for a good way to disable a JPanel. I'm using a MVC design for a Java Swing GUI. I want the JPanel to be disabled while the model is processin开发者_运维问答g stuff. I've tried setEnabled(false). That disables user input on the JPanel, but I'd like it to be grayed out to add a more visual effect.

Thanks in advance!


Have you looked into Glass Panes? They are useful for painting over areas which already contain components. Take a look


Disabling JPanel does not disable its children components by default, just blocks the panel. Solution I recommend is to create a JPanel subclass and override the setEnabled method like this:

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


JPanel doesn't appear any different when disabled, you'll have to override the paintComponent() method to draw it differently (or with a different color) when it is disabled. Something like this might work:

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


Since you want to apply a visual effect its better to use Glasspane. Check this article. SwingX already provides the components you need and much more. Check out the demo on the site for various components available.


Another solution is to use JXLayer framework. It is much more flexible then glass pane. Take a look at the project and this article

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜