I'm trying to simulate adding text to a JTextField
in code. I am doing this so I can automatically unit tests what happens when a user enters text.
I've tried the method shown below which worked for other simulations but not the JTextField
. How can I make it so the code below enters actionPerformed
method like it does in the GUI?
public class Main {
public static void main(String[] args) {
RemoteGUI remoteGUI = new RemoteGUI();
ActionEvent event = new ActionEvent(remoteGUI.getTextField(), ActionEvent.ACTION_PERFORMED, "50");
remoteGUI.getTextField().dispatchEvent(event);
System.out.println("Expected to perform action but didn't");
}
}
class RemoteGUI extends JFrame {
JTextField textField;
public RemoteGUI() {
JPanel panel = new JPanel();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(600, 250);
panel.setLayout(null);
this.add(panel);
Font font = new Font("Verdana", Font.BOLD, 28);
JLabel label = new JLabel("Enter A Number");
label.setFont(font);
label.setBounds(10,20,300,50);
panel.add(label);
textField = new JTextField("");
textField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String velocity = textField.getText();
System.out.println("Velocity " + velocity + " entered into GUI");
}
});
textField.setFont(font);
textField.setBounds(320,20,200,50);
panel.add(textField);
this.setVisible(true);
}
public JTextField getTextField(){
return textField;
}
}