Home > other >  Is there a way to remove that focus on the button in a JOptionPanel?
Is there a way to remove that focus on the button in a JOptionPanel?

Time:12-19

Is there a way to remove that focus on the button in a JOptionPanel? I really want to remove it. I looks a eyesore. There is my code for the JOptionPanel

JOptionPane.showMessageDialog(
                null,
                mainPanel,
                "CREDITS   (づ ̄ ³ ̄)づ ",
                JOptionPane.PLAIN_MESSAGE);

sample

CodePudding user response:

In this case you probably need a global event listener, to clear the focus when the message dialog appears. Here is an example:

import java.awt.AWTEvent;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.FocusEvent;

import javax.swing.FocusManager;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class TestFocus {

    private final AWTEventListener focusListener = this::removeFocus;
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new TestFocus()::initUI);
    }
    
    private void initUI() {
        Toolkit.getDefaultToolkit().addAWTEventListener(focusListener, AWTEvent.FOCUS_EVENT_MASK);
        JOptionPane.showMessageDialog(null, "Here is no Focus on button", "No focus!", JOptionPane.PLAIN_MESSAGE);
        Toolkit.getDefaultToolkit().removeAWTEventListener(focusListener); // to be safe remove it twice.
    }
    
    private void removeFocus(AWTEvent e) {
        if (e instanceof FocusEvent && ((FocusEvent) e).getID() == FocusEvent.FOCUS_GAINED) {
            Toolkit.getDefaultToolkit().removeAWTEventListener(focusListener);
            FocusManager.getCurrentKeyboardFocusManager().clearFocusOwner();
        }
    }
}
  • Related