How do we disable editing options on JDateChooser?

Nation Chirara picture Nation Chirara · May 14, 2015 · Viewed 8.1k times · Source

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);

        }
    });
    }
 }

Answer

trashgod picture trashgod · May 14, 2015

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:

set editable false

The alternative, chooser.setEnabled(false), has the effect of disabling the JDateChooser entirely.

set enabled false