I am using a JDateChooser
to allow the user to input date. How do I disable editing option on the text field that appears? I would not want the user to type anything in that text field - input should only be entered by clicking from the calendar. How do I achieve that?
Below is my code:
public class PQReport {
// product quotations report
public JPanel panel;
public PQReport() {
panel = new JPanel();
panel.setPreferredSize(new Dimension(125, 300));
initUI();
}
public void initUI() {
panel.setLayout(new net.miginfocom.swing.MigLayout());
JDateChooser chooser = new JDateChooser();
chooser.setLocale(Locale.US);
//chooser.isEditable(false);
chooser.setDateFormatString("yyyy-MM-dd");
panel.add(new JLabel("Date of Birth:"));
panel.add(chooser);
panel.add(new JButton("click"));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
PQReport rep = new PQReport();
JFrame f = new JFrame();
f.setSize(400, 400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(rep.panel);
}
});
}
}
One approach is to invoke setEditable(false)
on the chooser's IDateEditor
, JTextFieldDateEditor
.
JDateChooser chooser = new JDateChooser();
JTextFieldDateEditor editor = (JTextFieldDateEditor) chooser.getDateEditor();
editor.setEditable(false);
This allows a new date to be chosen, while forbidding changes via the JTextField
itself:
The alternative, chooser.setEnabled(false)
, has the effect of disabling the JDateChooser
entirely.
Alternatively, try this code that disables the JDateChooser
entirely:
JDateChooser chooser = new JDateChooser();
chooser.setEnabled(false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With