GetFocusOwner with a custom class

I need help working with getFocusOwner (). I have a Sudoku game that I created in Java and I want to add a cursor arrow to the program. I did some research and found that using a focus system would be a better way (if it is not, please give me a better way and I can investigate this).

Okay, so for testing purposes, I'm trying to focus on SetField, a custom class that extends JTextField (Custom because I wanted to disable any inputs that were not numbers). He is focused on focus. I called requestFocusInWindow () on SetField in the middle of the grid, and the focus is set to this component. The problem arises when I try to find a component that has focus.

This is what I do to check the getFocusOwner () method:

sGrid[40].requestFocusInWindow(); try{ System.out.println(this.getFocusOwner().getClass().getSimpleName()); } catch(NullPointerException e){ e.printStackTrace(); } 

No matter which component I'm trying to include, I always get a null pointer exception. I tried this with JButtons, JLabels and even with JPanels in my program. However, the focus is on the component. I see that the caret is blinking in the alleged SetField. Is there something I'm doing wrong? Thanks in advance for any help.

+4
source share
3 answers

Just found out the problem. For those who have problems with this, try using (Window) .getMostRecentFocusOwner (). It worked for me.

+1
source
  • Instead of a custom component that allows only numbers, only us JFormattedTextField.
  • You need to determine which component is focused, why not add KeyListener, MouseListener? I'm not quite sure what you are doing with focus, but it seems strange.
+1
source

I want to add a cursor key to the program.

You must use key bindings . Create a basic "ChangeFocusAction". You will need 4 instances of this class that you can map to KeyStroke.

Assuming you have an array of 81 text fields, your action can be created with an integer value that tells Action how to change focus. For instance:

right = -1
left = 1
up = -9
down = 9

The ActionEvent source will contain a text box with focus. Then you can find arry to find the offset of this text field. Then you add the int value on top of the index and request focus on that component.

+1
source

Source: https://habr.com/ru/post/1335017/


All Articles