Josué Almonasi
Josué Almonasi

Reputation: 143

Display JDateChooser in JOptionPane

I want to display a JDateChooser component inside an Option pane depending on some selection from the user. The point is that I tried getting the JDateChooser the way I want it to appear using next code:

JOptionPane.showInputDialog(null, new JDateChooser(),"Start date", JOptionPane.PLAIN_MESSAGE);

I tried with different kinds of JOptionPane variants but I can't figure out how to get this done, the user must be able to select the date and confirm by clicking a button so that I can retrieve that date and use it as a String.

I'd like to have something like this:

String s = JOptionPane.showInputDialog(null,"Text", "More Text", JOptionPane.INFORMATION_MESSAGE);

So that in that way I can get the selected date. I'm working with jcalendar-1.4.jar

Upvotes: 5

Views: 6870

Answers (2)

Jav13rzito
Jav13rzito

Reputation: 21

JDateChooser jd = new JDateChooser();
String message ="Choose start date:\n";
Object[] params = {message,jd};
if (JOptionPane.showConfirmDialog(this, params, "Start date", JOptionPane.PLAIN_MESSAGE) == 0) { 
    System.out.println("Picked date="+jd.getDate().toString());
    //I dont need to cast to a jdatechooser, i only take the date
    //start the chooser with todays date in case you want using jd.setCalendar(new GregorianCalendar());
}

Upvotes: 0

Josué Almonasi
Josué Almonasi

Reputation: 143

I finally reached a solution that worked for me. I stared creating separately a DateChooser and a String and put them together in an Object array, then pass the object as argument for the JOptionPane.

JDateChooser jd = new JDateChooser();
String message ="Choose start date:\n";
Object[] params = {message,jd};
JOptionPane.showConfirmDialog(null,params,"Start date", JOptionPane.PLAIN_MESSAGE);

In order to get the date once the user clicks the "OK" button in the JOptionPane I implemented a SimpleDateFormat.

String s="";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
s=sdf.format(((JDateChooser)params[1]).getDate());//Casting params[1] makes me able to get its information

That implementation solved the problem the way I wanted, I hope you guys find this helpful.

Upvotes: 5

Related Questions