[这个问题与这个问题有关]
设置:我有这个自制的“可编辑标签”组件,它看起来像一个标签,但是当您单击它时,它会变成一个可编辑字段,允许您对其进行编辑。您可以按 Esc 取消,或按 Shift-Enter 确定您的编辑 - 或单击可编辑字段下方的相应按钮。
挑战:当您进入此编辑模式时,我希望 UI 的其余部分完全被阻止:您应该取消或确定编辑,然后才能执行其他任何操作。在写这篇文章时,我意识到很明显:这正是对话框的操作方式——但我更喜欢我的“文档内”编辑标签,而不是打开对话框。
Glass pane might be the way to go. You can easily steal all the events and send some to your custom object. Here is an article that discusses a way to implement A wellbehaved glasspane.
这很粗糙。Swing 中没有任何方法可以阻止除一个组件之外的所有 UI。这是你必须自己建立的东西。这是我将使用的设计方法:
构建EditableLabelListener
定义方法的接口editableStateChanged(EditableLabelEvent)
创建一个EditableLabelEvent
扩展AWTEvent
并添加editableState
属性和isEditable()
布尔值的类。
为您的自定义组件添加方法addEditableLabelListener
和removeEditableLabelListener
在您使用组件的每个面板上,让您的控制器类(可能是您的面板,取决于您的设计)实现EditableEventListener
并将其自身注册为组件的侦听器。
触发事件时,控制器类应检查isEditable
事件的方法,并根据需要启用或禁用面板上的所有其他组件。当同一个表单上有多个可编辑的标签组件时,您可以使用getSource
事件上的方法来确定正在使用哪个,以便您可以禁用其他的。
In you editable label, when you start editing, use SwingUtilities.getRoot()
to get the root of your label, cast it to Container
. On the Container you can call getComponents()
. Iterate through this array and call setEnabled(false)
unless it is the label. Enable them when you're done editing.
One question: why do you need it? If you need dialog-like behavior, use JOptionPane
.
BTW, if you remove border from JTextField and setOpaque(false), it will be just as an editable label.
您可以扩展一个 JDialog,然后在初始化它时,
this.setAlwaysOnTop(true);
this.setModalityType(ModalityType.APPLICATION_MODAL);
this.setVisible(false);
this.setVisible(true);
它只允许与 JDialog 交互并阻止应用程序中的所有其他内容。