问题
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