阻止用户点击当前帧以外的其他地方的最佳方法? [英] Best way to block a user from clicking somewhere else than current frame?
问题描述
所以,我想知道,如何阻止用户退出或切换到应用程序中的另一个 JFrame?我还没有代码,但是这张图应该足够清楚了:
So, I was wondering, how to block user from exiting or switching to another JFrame in application? I don't have the code yet, but this picture should be clear enough:
那些灰色方块是 JFrame.上面有数字 2 的框架在上面,我希望它保持这种状态,直到我以编程方式关闭它.任何操作,例如点击编号为 1 的帧或尝试在编号为 2 的帧外执行任何操作,都应该导致再次关注编号为 2 的帧.
Those gray squares are JFrames. Frame with number 2 on it is on top, and I want it do stay that way until I programmatically close it. Any action like clicking on frame with number 1 or trying to do anything out of frame with number 2, should result in focusing on frame with number 2 again.
第 2 帧中的逻辑步骤是必不可少的,因此我想确保用户将填写该帧中的 from.
Step with logic in frame 2 is essential, so I want to make sure the user will fill in the from in the frame.
感谢您的宝贵时间!
推荐答案
如评论中所述,使用模态对话框将框架指定为所有者,用户将无法访问框直到对话框被关闭.
As mentioned in comments, use a modal dialog that specifies the frame as owner, and the user will not be able to access the frame until the dialog is dismissed.
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class BlockUserFromFrame {
BlockUserFromFrame() {
JFrame f = new JFrame("Try to access frame!");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JLabel l = new JLabel("Access frame after dialog disappears!");
l.setBorder(new EmptyBorder(50, 100, 50, 100));
f.add(l);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
// use a constructor that allows us to specify a parent and modality
JDialog d = new JDialog(f, true);
JLabel l1 = new JLabel("Dismiss dialog to access frame!");
l1.setBorder(new EmptyBorder(20, 100, 10, 100));
d.add(l1);
d.pack();
d.setLocationRelativeTo(f);
d.setVisible(true);
}
public static void main(String[] args) {
Runnable r = () -> {
BlockUserFromFrame o = new BlockUserFromFrame();
};
SwingUtilities.invokeLater(r);
}
}
这篇关于阻止用户点击当前帧以外的其他地方的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!