【发布时间】:2010-03-18 16:31:45
【问题描述】:
我正在寻找一种禁用 JPanel 的好方法。我正在为 Java Swing GUI 使用 MVC 设计。我希望在模型处理内容时禁用 JPanel。我试过 setEnabled(false)。这会禁用 JPanel 上的用户输入,但我希望它显示为灰色以增加视觉效果。
提前致谢!
【问题讨论】:
我正在寻找一种禁用 JPanel 的好方法。我正在为 Java Swing GUI 使用 MVC 设计。我希望在模型处理内容时禁用 JPanel。我试过 setEnabled(false)。这会禁用 JPanel 上的用户输入,但我希望它显示为灰色以增加视觉效果。
提前致谢!
【问题讨论】:
你看过玻璃板吗?它们对于在已经包含组件的区域上绘画很有用。 Take a look
【讨论】:
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());
}
}
【讨论】:
默认情况下禁用 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);
}
}
}
}
}
【讨论】:
既然您想应用视觉效果,最好使用 Glasspane。检查this article。 SwingX 已经提供了您需要的组件等等。查看网站上的演示,了解可用的各种组件。
【讨论】:
另一个解决方案是使用 JXLayer 框架。它比玻璃面板更灵活。看看项目和this的文章
【讨论】: