Controlling a focus when displaying a window - Java Swing

Java examples for Swing:JDialog

Introduction

setAutoRequestFocus from java.awt.Window class is used to specify whether a window should receive focus when it is displayed using either the setVisible or toFront methods.

Demo Code

import javax.swing.JFrame;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

class SecondWindow extends JFrame {
    //from   w  w  w  .j  a v  a2  s  .co m
    public SecondWindow() {
        this.setTitle("Second Window");
        this.setBounds(400, 100, 200, 200);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        this.setAutoRequestFocus(false);
    }
}
public class Main extends JFrame {

    private SecondWindow second;

    public Main() {
        this.setTitle("Example");
        this.setBounds(100, 100, 200, 200);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(new FlowLayout());
        
        second = new SecondWindow();
        second.setVisible(true);

        JButton secondButton = new JButton("Hide");
        this.add(secondButton);
        secondButton.addActionListener(event->second.setVisible(false));
 
        JButton thirdButton = new JButton("Reveal");
        this.add(thirdButton);
        thirdButton.addActionListener(event->second.setVisible(true));

        JButton exitButton = new JButton("Exit");
        this.add(exitButton);
        exitButton.addActionListener(event->System.exit(0));
    }
    public static void main(String[] args) {
        
        SwingUtilities.invokeLater(() ->{
                Main window = new Main();
                window.setVisible(true);
        });

    }
}

Related Tutorials