Java Swing How to - Create a Date picker from JSlider








Question

We would like to know how to create a Date picker from JSlider.

Answer

//from w w w  .j av  a 2  s  .  c o m
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Hashtable;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main extends JFrame {
    public final static Dimension RIGID_DIMENSION = new Dimension(1, 3);

    protected GregorianCalendar calendar = new GregorianCalendar();

    protected JLabel dateLabel;

    protected JSlider yearSlider = new JSlider(JSlider.HORIZONTAL, 1990, 2020, 2015);

    protected JSlider monthSlider = new JSlider(JSlider.HORIZONTAL, 1, 12, calendar
            .get(Calendar.MONTH) + 1);

    protected JSlider daySlider;

    protected Hashtable hashTable;

    protected SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, MMM d, yyyyy");

    public Main() {
        setSize(500, 340);

        Date currentDate = new Date();
        calendar.setTime(currentDate);

        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout(4, 1));

        JPanel p = new JPanel();
        p.setBorder(new TitledBorder(new EtchedBorder(), "Selected Date"));
        dateLabel = new JLabel(dateFormat.format(currentDate) + "     ");
        dateLabel.setFont(new Font("Arial", Font.BOLD, 24));
        p.add(dateLabel);
        p1.add(p);

        yearSlider.setPaintLabels(true);
        yearSlider.setMajorTickSpacing(5);
        yearSlider.setMinorTickSpacing(1);
        yearSlider.setPaintTicks(true);
        DateListener lst = new DateListener();
        yearSlider.addChangeListener(lst);

        p = new JPanel();
        p.setBorder(new TitledBorder(new EtchedBorder(), "Year"));
        p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
        p.add(Box.createRigidArea(RIGID_DIMENSION));
        p.add(yearSlider);
        p.add(Box.createRigidArea(RIGID_DIMENSION));
        p1.add(p);

        String[] months = (new DateFormatSymbols()).getShortMonths();
        hashTable = new Hashtable(12);
        for (int i = 0; i < 12; i++)
            hashTable.put(new Integer(i + 1), new JLabel(months[i],
                    JLabel.CENTER));
        monthSlider.setLabelTable(hashTable);
        monthSlider.setPaintLabels(true);
        monthSlider.setMajorTickSpacing(1);
        monthSlider.setPaintTicks(true);
        monthSlider.addChangeListener(lst);

        p = new JPanel();
        p.setBorder(new TitledBorder(new EtchedBorder(), "Month"));
        p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
        p.add(Box.createRigidArea(RIGID_DIMENSION));
        p.add(monthSlider);
        p.add(Box.createRigidArea(RIGID_DIMENSION));
        p1.add(p);

        int maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        daySlider = new JSlider(JSlider.HORIZONTAL, 1, maxDays, calendar
                .get(Calendar.DAY_OF_MONTH));
        daySlider.setPaintLabels(true);
        daySlider.setMajorTickSpacing(5);
        daySlider.setMinorTickSpacing(1);
        daySlider.setPaintTicks(true);
        daySlider.addChangeListener(lst);

        p = new JPanel();
        p.setBorder(new TitledBorder(new EtchedBorder(), "Day"));
        p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
        p.add(Box.createRigidArea(RIGID_DIMENSION));
        p.add(daySlider);
        p.add(Box.createRigidArea(RIGID_DIMENSION));
        p1.add(p);

        getContentPane().add(p1, BorderLayout.CENTER);

        WindowListener wndCloser = new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        };
        addWindowListener(wndCloser);

        enableEvents(ComponentEvent.COMPONENT_RESIZED);
        setVisible(true);
    }

    protected void processComponentEvent(ComponentEvent e) {
        if (e.getID() == ComponentEvent.COMPONENT_RESIZED) {
            int w = getSize().width;

            yearSlider.setLabelTable(null);
            if (w > 200)
                yearSlider.setMajorTickSpacing(5);
            else
                yearSlider.setMajorTickSpacing(10);
            yearSlider.setPaintLabels(w > 100);

            monthSlider.setLabelTable(w > 300 ? hashTable : null);
            if (w <= 300 && w >= 200)
                monthSlider.setMajorTickSpacing(1);
            else
                monthSlider.setMajorTickSpacing(2);
            monthSlider.setPaintLabels(w > 100);

            daySlider.setLabelTable(null);
            if (w > 200)
                daySlider.setMajorTickSpacing(5);
            else
                daySlider.setMajorTickSpacing(10);
            daySlider.setPaintLabels(w > 100);
        }
    }

    public void showDate() {
        calendar.set(yearSlider.getValue(), monthSlider.getValue() - 1, 1);
        int maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

        if (daySlider.getMaximum() != maxDays) {
            daySlider.setValue(Math.min(daySlider.getValue(), maxDays));
            daySlider.setMaximum(maxDays);
            daySlider.repaint();
        }

        calendar.set(yearSlider.getValue(), monthSlider.getValue() - 1, daySlider
                .getValue());
        Date date = calendar.getTime();
        dateLabel.setText(dateFormat.format(date));
    }

    class DateListener implements ChangeListener {
        public void stateChanged(ChangeEvent e) {
            showDate();
        }
    }

    public static void main(String argv[]) {
        new Main();
    }
}