我创建了JWindow,其中有几个JTextInput字段。此JWindow父级为JFrame。现在的情况-如果单击文本字段-它们将获得焦点,但JWindow也保持焦点。那很好。但是,如果我创建另一个JWindow(第一个JWindow的子代)并将其设置为可见,则将失去对第一个JWindow的关注,而子代JWindow将被聚焦。这不好。有什么方法可以保持对父JWindow的关注,并使子JWindowJTextInput字段那样获得焦点?

最佳答案

没有父级的JWindow永远不会是可聚焦的,仔细的话JTextComponents永远不会是可编辑的

例如

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();
            }
        });
    }
}

10-07 13:16