Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a JFrame to always be in focus

Tags:

java

swing

jframe

I want to make a JFrame that always has focus and cannot lose focus until it is closed, i already have it set to be always on top and i tried this code:

import java.awt.event.*;
import javax.swing.*;

public class Viewer extends JFrame WindowFocusListener
{
    public Viewer()
    {
        addWindowFocusListener(this);
        setAlwaysOnTop(true);
        this.setFocusable(true);
        this.setFocusableWindowState(true);
        panel = new JPanel();

        setSize(WIDTH,HEIGHT);
        setLocation(X,Y);
        setResizable(false);
        setVisible(true);
    }

    public void windowGainedFocus(WindowEvent e){}
    public void windowLostFocus(WindowEvent e)
    {
        toFront();
        requestFocusInWindow();
        System.out.println("focus lost");
    }

    private JPanel panel;
    private static final int WIDTH = 200;
    private static final int HEIGHT = 200;
    private static final int X = 100;
    private static final int Y = 100;

    public static void main(String args[]){new Viewer();}
}

I don't see why this code won't work, can anyone see what I'm doing wrong? thanks in advance.

like image 380
John Avatar asked Feb 02 '26 23:02

John


1 Answers

This is not possible with a simple JFrame; this is a job for JDialog. Please see these implemented methods:

setModal()

setModalityTypes()

like image 114
mKorbel Avatar answered Feb 04 '26 11:02

mKorbel