Is there a postActionEvent version for KeyEvent (specifically for JTextArea)?

I am writing a program containing several JTextFields and 2 JTextAreas inside an input panel. I have a submit button below. I configured it so that when the user types something in each field (including JTextAreas) and presses the Enter key, he updates the text file, and when he presses the submit button, he updates the file and then displays a new version of the local directory.

If the user presses Enter in any of the fields, he checks their input, however I want to re-check all the fields when they press the submit button. Each field (again, JTextAreas is included) has its own validation check inside its ActionListener or KeyListener (for JTextAreas). It is simple enough to use postActionEvent () for JTextFields, but is there a similar method for JTextAreas to force Fire KeyEvent? . I don't want to duplicate code and consume memory by rewriting validation for these 2 components inside an ActionEvent for JButton.

Unfortunately, I cannot provide a sample because I am writing a program on a secret machine (PC).

+4
source share
2 answers

You can simulate ENTER by clicking using the Robot class keyPress(..) and keyRelease(..) methods. Of course, you will need to go through all the JTextAreas on the component and call requestFocusInWindow(..) , followed by a simulated keypress ( Exception handling omitted):

 Robot robot = new Robot();//throws AWTException ... Component[] components=getContentPane().getComponents(); for(int i=0;i<components.length;i++) { if(components[i] instanceof JTextArea) { components[i].requestFocusInWindow(); simulateEnter(); } } public static void simulateEnter() { robot.keyPress(KeyEvent.VK_ENTER); robot.keyRelease(KeyEvent.VK_ENTER); } 
+3
source

Why try to publish a KeyEvent to trigger validation when you can just call your validate method, for example. in pseudo code

 myTextArea.getDocument().addDocumentListener(){ //in each of the method you call validate } private function validate( ){ //do your validation } private function submitButtonFunction(){ validate(); } 

Also note that it is recommended to use a DocumentListener if you want to respond to input in a JTextComponent . For example, your KeyListener will not KeyListener after drag and drop. Depending on the implementation of your KeyListener , this may also fail if you use copy-paste.

+4
source

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


All Articles