I want to create separate year, month, and day entry text fields in order to properly format my date string into a format accepted by my SQL query (yyyy-MM-dd). My solution to this problem is simply to have the user divide all 3 of these into separate fields, so I can manually reformat them in the back-end. What I would like to do is have each text field display the format initially, but when clicked, would clear the text field for input. For example, when the year text field is not selected, I want it to display "YYYY" (even if it was never selected to begin with) and when it is selected, to clear the text for input. As you'll see below I also limited my year text field to 4 characters as well.
dateOfPurchaseTextField = new JTextField();
dateOfPurchaseTextField.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent arg0) {
if (dateOfPurchaseTextField.getText() == "YYYY") {
dateOfPurchaseTextField.setText("");
}
}
@Override
public void focusLost(FocusEvent e) {
dateOfPurchaseTextField.setText("YYYY");
}
});
dateOfPurchaseTextField.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
if (dateOfPurchaseTextField.getText().length() >= 4) {
if (e.getKeyCode() != 8 && e.getKeyCode() != 46)
e.consume();
}
}
});
dateOfPurchaseTextField.setHorizontalAlignment(SwingConstants.CENTER);
dateOfPurchaseTextField.setFont(new Font("Tahoma", Font.PLAIN, 14));
dateOfPurchaseTextField.setColumns(10);
dateOfPurchaseTextField.setBounds(819, 603, 46, 22);
inventoryFrame.getContentPane().add(dateOfPurchaseTextField);
When I run my page, the "YYYY" does not initially pop up, however, once it has been selected and then subsequently deselected, it will then show the "YYYY" from then on. My alternative solution to get "YYYY" to initially appear was to set the value initially to "YYYY" but when that happens, the text value doesn't clear when the text box is selected. How can I fix this?
On a side note, if anyone has a more efficient way of getting the text field's date to always be in "yyyy-MM-dd" format, I'd love to know! Thanks in advance!
Edit: This question is different than the one provided, as the solution is completely different, and while that question was asking how the entire process was done, this question was merely asking why the "YYYY" placeholder was never initially displayed to begin with.