How to set window always on top of any other appli

2019-07-09 04:55发布

问题:

I have a JFrame which needs to be always on top of the other application. For this I am using setAlwaysOnTop() method of Window class.

Here is my code :

class Test1 extends JFrame {

    public Test1() {
        initComponents();
        setTitle("Top Window");
        setAlwaysOnTop(true);
    }


    private void initComponents() {
        jLabel1 = new JLabel();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
        jLabel1.setText("I am a top most window");
        getContentPane().add(jLabel1, BorderLayout.CENTER);

        pack();
    }                     

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Test1().setVisible(true);
            }
        });
    }

    private javax.swing.JLabel jLabel1;
}

This works fine with some of the other application such as notepad, explorer etc, i.e. when my application is above notepad everything works fine.

But when my java application goes above any application that is already on top such as task manager. Then the method setAlwaysOnTop() doesn't works.

What I need is any way through which I can make my application always on top.

I have also searched many other related posts on stackoverflow but none seems to answer my question. I have also tried other ways such as overriding the windowDeactivated(WindowEvent e) method

addWindowListener(new WindowAdapter(){
    @Override
    public void windowDeactivated(WindowEvent e) {
        toFront();
        //requestFocus();
        //requestFocusInWindow();
    }
});

but this also doesn't worked.

Is there any other way through which I can may my JFrame always on top of every other application except in case of full screen applications.

回答1:

It depends on the operating system. In general, you can't guarantee that your window will always be on top when it comes to native windows, nor should you. The task manager is always-on-top for good reasons.

I remember that some versions of Vista and older Windows systems allowed that and the native and Java windows ended up fighting for focus.