Stop newly created dialog from taking focus

假装没事ソ 提交于 2019-12-21 20:45:54

问题


I'm trying to have Java Swing dialog be created but I don't want to have the dialog to take focus away from whatever is currently focused. So for example, if you're editing a word doc and a different application creates a dialog, you should see the dialog but the word doc should remain in focus so that you can keep editing.

I've tested the following code on Mac OSX and on Ubuntu 12.04. On Mac, the code creates dialogs that do not take the focus like I want. On Ubuntu, the dialogs take the focus, and I can't type while they are being created.

I really hope this isn't operating system specific. Is there any way to achieve what I'm trying to do on all platforms (or at least Ubuntu)?

import javax.swing.*;
import java.awt.Color;
import java.util.Random;

public class Focus {
    private static Random r = new Random();

    public static void main(String[] args) {
        while(true) {   
            try {
                Thread.sleep(500);
                createObject(r.nextInt(1000), r.nextInt(600));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void createObject(int x, int y) {
        JDialog testDialog = new JDialog();
        testDialog.setSize(50, 50);
        testDialog.setLocation(x, y);
        testDialog.setAlwaysOnTop(true);
        testDialog.setUndecorated(true);
        testDialog.setFocusable(false);
        testDialog.setEnabled(false);
        testDialog.setVisible(true);
    }
}

回答1:


Maybe:

testDialog.setFocusableWindowState(false);


来源:https://stackoverflow.com/questions/14668010/stop-newly-created-dialog-from-taking-focus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!