Issue
I have a jTextField called fecha, by default, it has a text "dd/mm/aaaa" to show the user how to fill it, i've added an event for when it's clicked or has gained the focus it's text disappears. I want to use a shortcut as ctrl + A for filling the jTextField with the actual date.
Solution
UPDATE:
To get today's date you can use this method:
java.time.LocalDate.now()
You can use this to set the text inside the JTextField as today's date when 'Ctrl + A' gets pressed.
import java.awt.GridBagLayout;
import java.awt.event.*;
import javax.swing.*;
public class test {
public static void main(String[] args) {
JTextField fecha = new JTextField(10);
/* add a new action named "foo" to the panel's action map */
fecha.getActionMap().put("foo", new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
fecha.setText(java.time.LocalDate.now().toString());
}
});
InputMap inputMap = fecha.getInputMap();
KeyStroke controlA = KeyStroke.getKeyStroke("control A");
inputMap.put(KeyStroke.getKeyStroke(Character.valueOf('a'), 0), "foo");
inputMap.put(controlA, "foo");
/* display the panel in a frame */
JFrame frame = new JFrame();
frame.getContentPane().add(fecha);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.setSize(400, 400);
frame.setVisible(true);
}
}
Answered By - Mark Santos