Reputation: 1077
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:
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.
Step with logic in frame 2 is essential, so I want to make sure the user will fill in the from in the frame.
Thank you for your time!
Upvotes: 0
Views: 611
Reputation: 168825
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);
}
}
Upvotes: 2