有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将焦点设置为其他jframe

我的问题与java swing框架有关。我有一个J2框架。jFrame1和jFrame2。jframe 1中有一个jbutton,因此当用户单击jbutton时,我希望将焦点放在第2帧(第2帧已加载到应用程序中)不关闭框架1。请帮忙做这件事


共 (1) 个答案

  1. # 1 楼答案

    您可以使用^{}将当前帧置于前面:

    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    
    public class MyFrame extends JFrame implements ActionListener {
        public MyFrame(String title) {
            super(title);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            JButton button = new JButton("Bring other MyFrame to front");
            button.addActionListener(this);
            add(button);
            pack();
            setVisible(true);
        }
    
        public static void main(String[] args) {
            new MyFrame("1");
            new MyFrame("2");
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            for (Window window : Window.getWindows()) {
                if (this != window) {
                    window.toFront();
                    return;
                }
            }
        }
    }