I have created JWindow
, which has several JTextInput
fields. This JWindow
parent is JFrame
. Now the situation - if text fields are clicked - they get the focus BUT JWindow
also stays focused. That is good. But if I create another JWindow
(child of first JWindow
), and set it visible, then focus on first JWindow
is lost, and the child JWindow
is focused. This is bad. Is there some way to retain focus on the parent JWindow
, and to make the child JWindow
get the focus like JTextInput
fields?
Make JWindow retain focus when children are focused, including another window as child
814 views Asked by Ernestas Gruodis At
2
There are 2 answers
3
On
JWindow without parent never will be focusable, carefully then JTextComponents never will be editable
for example
import java.awt.*;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class WindowTest {
private JFrame frame;
private boolean bol = true;
public WindowTest() {
frame = new JFrame("Window Test");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
JWindow win = new JWindow(frame);
win.setLayout(new GridLayout(0, 1));
JTextField text = new JTextField("Show Window");
text.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
if (!bol) {
JWindow win = new JWindow();
win.setLayout(new GridLayout(0, 1));
win.add(new JTextField("JTextField"));
win.add(new JTextField("JTextField"));
win.add(new JLabel("<html> Concurency Issues in Swing<br>"
+ " never to use Thread.sleep(int) <br>"
+ " durring EDT, simple to freeze GUI </html>"));
win.pack();
win.setLocation(350, 150);
win.setVisible(true);
bol = true;
}
}
@Override
public void removeUpdate(DocumentEvent e) {
}
@Override
public void changedUpdate(DocumentEvent e) {
}
});
win.add(text);
win.add(new JTextField("JTextField"));
win.add(new JTextField("JTextField"));
win.pack();
win.setLocation(250, 150);
win.setVisible(true);
bol = false;
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new WindowTest();
}
});
}
}
Before setting the child window visible, add a
WindowListener
. After you callsetVisible
on the child window, you'll receive thewindowActivated
callback. At that point calltoFront
on your parent window to bring it forward. Given the quirkiness of OS z-order handling, you might need/want to calltoBack
on the child window first, as well as callingrequestFocus
on the parent window or one of its focusable children afterward.