0

I have constructed the following JDateChooser:

availFromDate = new JDateChooser();
availFromDate.setDateFormatString("dd/MM/yyyy");
JTextFieldDateEditor dateEditor = (JTextFieldDateEditor)availFromDate.getComponent(1);
dateEditor.setHorizontalAlignment(JTextField.RIGHT);
availFromDate.setSize(new Dimension(50, 0));
availFromDate.add(availablefromT);
calendarP.add(availFromDate);
contentPane.add(calendarP);
frame1.add(contentPane);
frame1.setVisible(true);

However, I need the date selected from the JDateChooser to appear in the JTextField it is being held in. I realise there must be a getDate() method involved, though I am not sure how to implement it.

How do I obtain the date and display it within the textfield in the format of dd/MM/yyyy?

Edit:

I have tried the following after seeing suggestions:

  SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
  String date = sdf.format(availFromDate.getDate());
  availablefromT.setText(date);

Though, now I am getting a NullPointerException. Anyone know why? It seems to concern this: String date = sdf.format(availFromDate.getDate());

The Error(s):

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at java.util.Calendar.setTime(Calendar.java:1770)
    at java.text.SimpleDateFormat.format(SimpleDateFormat.java:943)
    at java.text.SimpleDateFormat.format(SimpleDateFormat.java:936)
    at java.text.DateFormat.format(DateFormat.java:345)
    at Controller.makeCustEnquiryGUI(Controller.java:2061)

Example:

import com.toedter.calendar.JDateChooser;
import com.toedter.calendar.JTextFieldDateEditor;
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import javax.swing.*;
import java.util.*;

public class CalendarTest {

    private JFrame chooseCruiseFrame;
    private JDateChooser availFromDate;
    private JTextField availablefromT;
    private JPanel contentPane;
    private JPanel centerP;

    public static void main(String[] args) {
        new CalendarTest();
    }

    public CalendarTest() {

        //////////// Creating Frame
        chooseCruiseFrame = new JFrame("");
        chooseCruiseFrame.setSize(300, 200);
        chooseCruiseFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        chooseCruiseFrame.setVisible(true);

        //////////// Creating contentPane
        contentPane = new JPanel(new GridLayout(0, 1));
        contentPane.setBackground(new java.awt.Color(255, 255, 255));
        chooseCruiseFrame.add(contentPane);
        chooseCruiseFrame.setVisible(true);

        //////////// Creating CenterP
        centerP = new JPanel();
        centerP.setBackground(new java.awt.Color(255, 255, 255));
        contentPane.add(centerP);
        chooseCruiseFrame.add(contentPane);
        chooseCruiseFrame.setVisible(true);

        // Available From Calendar
        JLabel availF = new JLabel("Available From:");
        centerP.add(availF);
        contentPane.add(centerP);
        availablefromT = new JTextField(11);
        centerP.add(availablefromT);
        contentPane.add(centerP);
        chooseCruiseFrame.add(contentPane);
        chooseCruiseFrame.setVisible(true);

        availFromDate = new JDateChooser();
        JTextFieldDateEditor dateEditor = (JTextFieldDateEditor) availFromDate.getComponent(1);
        dateEditor.setHorizontalAlignment(JTextField.RIGHT);
        availFromDate.add(availablefromT);
        centerP.add(availFromDate);
        contentPane.add(centerP);
        chooseCruiseFrame.add(contentPane);
        chooseCruiseFrame.setVisible(true);

        // Converting Date to String
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
        String date = sdf.format(availFromDate.getDate());
        availablefromT.setText(date);
    }
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Freddy
  • 683
  • 4
  • 35
  • 114
  • 1
    Look at [`DateFormat`](https://docs.oracle.com/javase/8/docs/api/java/text/DateFormat.html) and try something before you get back to us. Also, for better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). – Andrew Thompson Feb 07 '15 at 01:04
  • 1
    My guess is you start by calling JDateChooser#getDate to get the Date object been managed by the field, you then use a SimpleDateFormat to format the Date to your requirements – MadProgrammer Feb 07 '15 at 01:05
  • 1
    BTW - `availFromDate.setSize(new Dimension(50, 0));` A height of `0` is illogical. But then.. See [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/q/7229226/418556) (Yes.) – Andrew Thompson Feb 07 '15 at 01:14
  • Thank you for comments! @AndrewThompson, my apologies, I will make sure I SSCCE in the future. – Freddy Feb 07 '15 at 20:32
  • Also, @MadProgrammer, I have tried your suggestion, and seem to be running across a NullPointerException, I have edited my post to display the issue, I may have misinterpreted what you was suggesting, but it'll be great if you can see the edit to identify my mistake. And of course, thank you for the help! – Freddy Feb 07 '15 at 20:34
  • 1
    *"Though, now I am getting a NullPointerException. Anyone know why?"* without a [runnable example](https://stackoverflow.com/help/mcve) which demonstrates your problem it could any thing – MadProgrammer Feb 07 '15 at 20:49
  • `availFromDate.getDate()` seems to be returning a `null`. Want to provide a runnable example which demonstrates your problem? – MadProgrammer Feb 11 '15 at 00:09
  • @MadProgrammer, my apologies, I thought you were asking for the list of errors. I have updated my edit yet again, hopefully with what you're looking for. – Freddy Feb 11 '15 at 00:23
  • When you call `availFromDate.getDate()`, no date has yet been selected, therefore it's `null`. You need to wait till something is selected before trying to format the value (and you should be checking for a `null` result). Also `availFromDate.add(availablefromT);` doesn't make sense – MadProgrammer Feb 11 '15 at 00:35
  • @MadProgrammer, I see the problem now that you have mentioned it. Would you suggest a 'MouseListener' to go around this? Also 'availFromDate.add(availablefromT);' ... I assumed this is required in order to ensure the JDateChooser is essentially connected the JTextField? – Freddy Feb 11 '15 at 01:12
  • *" I assumed this is required in order to ensure the JDateChooser is essentially connected the JTextField?"* - Ah, no, you've already added `availablefromT` to your frame and `JDateChooser` already has it's own `JTextField`...*"Would you suggest a 'MouseListener' to go around this?"* - Nope, I'd recommend a `PropertyChangeListener`, you should be listening for "date" I think – MadProgrammer Feb 11 '15 at 01:20

6 Answers6

2

the same code works here

   //button    

        private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        DateFormat fmt = new SimpleDateFormat("dd/MM/yyyy");
        String date = fmt.format(this.txt_data_ini.getDate()); //jdatechooser
        this.teste.setText(date);

    }  
Fernando
  • 36
  • 1
2

great attention for JDateChooser into JCalendar.jar v.1.4: Getting the "SelectedDate" of the Date picker in this way (after using a statement to create an JDataChooser object named dataEmissioneTextField):

 Date date = dataEmissioneTextField.getDateEditor().getDate();

In the case we want to choose a date with a specific listener to save the value of the selected date we can write as follows:

dataEmissioneTextField.getDateEditor().addPropertyChangeListener(new PropertyChangeListener() {
    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        // TODO Auto-generated method stub
        if ("date".equals(evt.getPropertyName())) {
            //Get the selected date 
            Date date = dataEmissioneTextField.getDateEditor().getDate();
            dataConsegnaTextField.setDate(dataConsegnaTextField.getDateEditor().getDate());
            ordine.setOrderDeliveryDate(date);
            //Draws a Green Border when the date is selected 
            dataEmissioneTextField.setBorder(BorderFactory.createLineBorder(Color.GREEN));
        } else {
            //Draws a Red Border when the date is not selected  
            dataEmissioneTextField.setBorder(BorderFactory.createLineBorder(Color.RED));
        }
    }
});

Note that the JDateChooser supports just a PropertyChangeListener.

Regards.

1

To use jCalendar, you can use the code below.

String jcalender=calendar.getDate().toString();
label.setText(jcalender);
woliveirajr
  • 9,433
  • 1
  • 39
  • 49
0

Ok,so,you have JDateChooser and JTextField. You will need something to trigger the change,so that date would go to text. First of all, you need to create a new instance that is object class. When you do this,call method getData(find it on the web) and store it into your object variable. Then you create new variable that is string and store object there. And last,show text in JTextField.

So the code should look like this:

public Object x;
public string y;
x = getData(availFromDate);
y = x.toString();
JTextField.setText(y);

If this doesnt work, try :

y = string.valueOf(availFromDate);
enter code here
Vulovic Vukasin
  • 1,540
  • 2
  • 21
  • 30
0

you can do like

 public void jdatechooserexample() {
   JDateChooser chooser=new JDateChooser();
    JTextField field=new JTextField(15);
       chooser.addPropertyChangeListener("date",new PropertyChangeListener  () { 
     public void propertyChange(PropertyChangeEvent e){
     JDateChooser chooser=(JDateChooser)e.getSource();
      SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");
      field.setText(sdf.format(chooser.getDate()));

 }
 });
 }
Deepak Singh
  • 460
  • 2
  • 7
  • 19
0

JDateChooser Only works with Property change event. This can be used to display the value in Jtextfield

    private void jDateChooser1PropertyChange(java.beans.PropertyChangeEvent evt) { 
    if ("date".equals(evt.getPropertyName())) {
                //Get Date
                Date date = jDateChooser1.getDateEditor().getDate();
                SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy");
//Define the format of Date
                String mydate = sf.format(date);
                jTextField1.setText(mydate);


            } else {
               jTextField1.setText(null);

            }
    }