I'm not sure about the keyboard focus

I want the text editor to have keyboard focus under certain conditions within renderOpenGL().
I put the following code in renderOpenGL()

if (myTextBox.isVisible() && !isPlay)
{
    myTextBox.setWantsKeyboardFocus(true);
    myTextBox.grabKeyboardFocus();
    int o = myTextBox.hasKeyboardFocus(true);
    LOG(juce::String(o));
}

(*isPlay determines if playback is in progress.)

myTextBox.setVisible(true) when the screen is clicked.
The first click does not focus, the second click does. I am having trouble understanding what the heck is going on.

Is there any way to get it to focus on the first click? Any help would be appreciated.

It might be worth stepping through he code with a debugger to see what happens in grabKeyboardFocus().

When you say…

myTextBox.setVisible(true) when the screen is clicked.

Is it possible this is happening after the call to grabKeyboardFocus()? if it is the component will fail to take focus while it’s not visible.

I’d brute force it and try to schedule the grabFocus call into the next cycle. you can use MessageManager::callAsync for that and just need to check if the component got deleted.

Thanks for the suggestion.
I have looked into it, but no matter how much I try to grabKeyboardFocus, it focuses to “Settings…” is focused to “Settings…”.
I used juce::MessageManager::callAsync([this]) and the result was the same.

It monitors where the focus is at each render update and at the moment of click.

void Anime_testAudioProcessorEditor::mouseDown(const juce::MouseEvent& e)
{
click_n += 1;
if (click_n == 2) return;

juce::Component* focusedComponent = juce::Component::getCurrentlyFocusedComponent();
if (focusedComponent != nullptr)
{
    juce::String componentName = focusedComponent->getName();
    LOG(juce::String(componentName));
}
else
{
    LOG("No_Focus");
}

Curiously, if the second click is written to do nothing at all, the focus switches to the text editor on the second click.
The following processing performed in the render
myTextBox.setWantsKeyboardFocus(true);
myTextBox.grabKeyboardFocus();
are suddenly enabled.(*Of course, I’m not clicking on a text editor.)

When I try to give focus to a specific component in a render, the focus is suddenly enabled when I call a method that removes awareness from OpenGL.
I am currently aware that this is such a bug, but I continue to solicit information.

Thanks for the advice, and I’ll keep you posted.

I recently had an issue where using grabKeyboardFocus() wouldn’t work no matter how hard I tried. Turned out another component in the same space had an empty KeyPressed callback inherited from KeyListener. Deleting that fixed my keyboard focus issues

1 Like