awt
Prevent an Application Window or Component from gaining focus
With example we are going to see how to prevent a window and a graphical object from gaining focus in a Java Desktop Application.
This is very simple, as the only thing you have to do is:
- Call
setFocusable(false)to prevent a component from gaining focus. - Call
setFocusableWindowState(false)to prevent a window from gaining focus. - Call
getCurrentKeyboardFocusManager().clearGlobalFocusOwner()to remove the focus from the application.
Let’s see the code snippets that follow:
package com.javacodegeeks.snippets.desktop;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Component;
import java.awt.Frame;
import java.awt.KeyboardFocusManager;
import java.awt.TextArea;
public class FocusPrevention {
public static void main(String[] args) {
// Create frame with specific title
Frame frame = new Frame("Example Frame");
// Create a component to add to the frame; in this case a text area with sample text
Component textArea = new TextArea("Sample text...");
// Create a component to add to the frame; in this case a button
Component button = new Button("Click Me!!");
// Add the components to the frame; by default, the frame has a border layout
frame.add(textArea, BorderLayout.NORTH);
frame.add(button, BorderLayout.SOUTH);
// prevent the button from gaining the focus
button.setFocusable(false);
// prevent the window from gaining the focus
frame.setFocusableWindowState(false);
// Remove the focus from the application
KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
// Show the frame
int width = 300;
int height = 300;
frame.setSize(width, height);
frame.setVisible(true);
}
}
This was an example on how to prevent an Application Window or Component from gaining focus.

