Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we disable editing options on JDateChooser?

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

        }
    });
    }
 }
like image 316
CN1002 Avatar asked May 14 '15 10:05

CN1002


2 Answers

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

like image 198
trashgod Avatar answered Nov 08 '22 04:11

trashgod


Alternatively, try this code that disables the JDateChooser entirely:

JDateChooser chooser = new JDateChooser();
chooser.setEnabled(false);

image

like image 29
Madhuka Dilhan Avatar answered Nov 08 '22 05:11

Madhuka Dilhan