Sunday, February 23, 2014

Using JCalender with Visual Swing in Eclipse

Visual Swing doesn't allow new components to be added to palette like Window Builder does. So I couldn't just drag and drop JDateChooser like I did other Swing components. These are steps to add a simple Date Picker to your Visual Swing JFrame. I used JCalender 1.4.

Note: Link to install Visual Swing on Eclipse.

1) Download and add JCalender JAR to classpath.

2) In your class that extends JFrame class, add a private variable along side the list of other variables (components like JLabel, JTextField, JComboBox etc) that Visual Swing auto creates when you drag and drop them onto the visual JFrame window.
private JDateChooser myDateChooser;
Visual Swing uses Getter to instantiate the compenents whereas Window Builder instantiates directly in the initComponents() method. Use the following getter for visual swing.
private JDateChooser getMyDateChooser(){
if(myDateChooser ==null) {
myDateChooser = new JDateChooser();
                        myDateChooser.setDate(new Date());  }
return myDateChooser;
You can register for any events here or set some default date like I did above.

3) Now we need to add this myDateChooser to the JFrame. This is done in the initComponents() method where Visual Swing adds all the other components to the JFrame. The following piece of code will do, make sure you are using proper coordinates inorder to place the Date Picker in the right place on JFrame.
add(getToDateChooser(), new Constraints(new Leading(550, 110, 12, 12), new Leading(60, 12, 12)));
That's it. Now your Date Picker is ready. Make sure to grab the date chosen by the user using some action event listener say a button click in my case. In order to grab the date, all you need is
Calender selectedDate = myDateChooser.getCalendar();
That's it, you can set a default date  and grab the user selected date simply by the getter and setter of JDateChooser.

No comments:

Post a Comment

Fork me on GitHub