Java Swing How to - Send the JFrame to front of screen








Question

We would like to know how to send the JFrame to front of screen.

Answer

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*from www . ja va  2  s . c  om*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.Timer;

public class Main {
  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JButton button = new JButton("Bring me to top after 3 seconds");
    button.addActionListener(e -> triggerBringToFront(f, 3000));
    f.getContentPane().add(button);

    f.pack();
    f.setVisible(true);
  }

  private static void triggerBringToFront(final JFrame f, final int delayMS) {
    Timer timer = new Timer(delayMS, new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        // This will only cause the task bar entry
        // for this frame to blink
        // f.toFront();

        // This will bring the window to the front,
        // but not make it the "active" one
        // f.setAlwaysOnTop(true);
        // f.setAlwaysOnTop(false);

        if (!f.isActive()) {
          f.setState(JFrame.ICONIFIED);
          f.setState(JFrame.NORMAL);
        }
      }
    });
    timer.setRepeats(false);
    timer.start();
  }
}