如何将JFrame设置为始终处于焦点

时间:2011-12-25 19:27:55

标签: java swing jframe

我想创建一个始终具有焦点的JFrame,并且在关闭之前不能失去焦点,我已经将它设置为始终位于顶部并尝试此代码:

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();}
}

我不明白为什么这段代码不起作用,谁能看到我做错了什么?提前谢谢。

1 个答案:

答案 0 :(得分:9)

使用简单JFrame无法做到这一点;这是JDialog的工作。请参阅这些实施的方法:

setModal()

setModalityTypes()