I'm writing a program that contains multiple JTextFields and 2 JTextAreas within an input panel. I have a submit button on the bottom. I have it set up so when a user types something into each field (including the JTextAreas) and hits the Enter key, it updates a text file, and when they press the submit button it updates the file then outputs a new version of it in the local directory.
If the user presses Enter in any of the fields, it validates their input, however, I want to re-validate all fields when they press the submit button. Each field (again, JTextAreas included) has it's own validation check within its ActionListener or KeyListener (for the JTextAreas). It's easy enough to use postActionEvent() for the JTextFields, but is there a similar method for the JTextAreas to force fire a KeyEvent? I don't want to duplicate code and consume memory by re-writing the validation for those 2 Components inside the ActionEvent for the JButton.
Unfortunately, I can't provide a sample because I'm writing the program on a classified machine (PC).
You could simulate ENTER being pressed using Robot
class keyPress(..)
and keyRelease(..)
methods. You would of course have to iterate through all JTextAreas
on the component and call requestFocusInWindow(..)
followed by the 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);
}