Java JFrame set auto focus

Description

Java JFrame set auto focus

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 {

   public SecondWindow() {
      this.setTitle("Second Window");
      this.setBounds(400, 100, 200, 200);
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      this.setAutoRequestFocus(false);
   }//from   w  w w.  j a v a  2  s  .co  m
}

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(new ActionListener() {
         public void actionPerformed(ActionEvent event) {
            second.setVisible(false);
         }
      });

      JButton thirdButton = new JButton("Reveal");
      this.add(thirdButton);
      thirdButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent event) {
            second.setVisible(true);
         }
      });

      JButton exitButton = new JButton("Exit");
      this.add(exitButton);
      exitButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent event) {
            System.exit(0);
         }
      });
   }

   public static void main(String[] args) {

      SwingUtilities.invokeLater(new Runnable() {

         @Override
         public void run() {
            Main window = new Main();
            window.setVisible(true);
         }
      });

   }
}



PreviousNext

Related