Java focuses on frames

Could you help me with this? I have a JDialog with some text fields, checkboxes, and buttons. I want to disappear when the frame no longer focuses. So I added a focus listener to JDialog, and when the focus is lost, I call dialog.setVisible(false); . The problem is that if I click on the checkbox, text box or button, the frame loses focus and disappears. How can I focus it until the user closes it?

EDIT: The "frame", I mean, is JDialog. I do not use Frame or JFrame. All components are hosted on JDialog. I want it to hide when it is not focused, but keep it focused until the user closes it.

+4
source share
3 answers

It looks like you added the wrong listener, what you should add is addWindowFocusListener (...) , see this small sample program, this is what you want:

 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class DialogFocus { private JFrame frame; private MyDialog myDialog; public DialogFocus() { } private void createAndDisplayGUI() { frame = new JFrame("JFRAME"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationByPlatform(true); myDialog = new MyDialog(frame, "My Dialog", false); JButton showButton = new JButton("SHOW DIALOG"); showButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (!(myDialog.isShowing())) myDialog.setVisible(true); } }); frame.add(showButton, BorderLayout.PAGE_END); frame.setSize(300, 300); frame.setVisible(true); } public static void main(String\u005B\u005D args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new DialogFocus().createAndDisplayGUI(); } }); } } class MyDialog extends JDialog { private WindowFocusListener windowFocusListener; public MyDialog(JFrame frame, String title, boolean isModal) { setTitle(title); setModal(isModal); JPanel contentPane = new JPanel(); JTextField tfield = new JTextField(10); JComboBox cbox = new JComboBox(); cbox.addItem("One"); cbox.addItem("Two"); cbox.addItem("Three"); contentPane.add(tfield); contentPane.add(cbox); windowFocusListener = new WindowFocusListener() { public void windowGainedFocus(WindowEvent we) { } public void windowLostFocus(WindowEvent we) { setVisible(false); } }; addWindowFocusListener(windowFocusListener); add(contentPane); pack(); } } 
+5
source

Make the dialog modal, then the user cannot click on the frame.

+2
source

Check FocusEvent it has public Component getOppositeComponent() . If the opposite component is a child component of JDialog, do not hide the dialog box.

+2
source

Source: https://habr.com/ru/post/1401757/


All Articles