如何从JSpinner结果值设置Calendar?

时间:2012-10-09 12:27:22

标签: java swing jspinner jcalendar

我正在尝试制作日历月份和年份选择器。

如何从两个jspinner设置日历?

jspinner 1 =月份值

jspinner 2 =年份值

也许它只是从jspinner获取int值.. 怎么做?

这是我的代码: (更新)

import java.awt.BorderLayout;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSpinner;
    import javax.swing.SpinnerDateModel;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;


    public class datepicker extends JFrame{
       JSpinner Smonth = new JSpinner();
       JSpinner Syear = new JSpinner();
       Calendar cal = Calendar.getInstance();
       Date date = cal.getTime();
       SimpleDateFormat sdf_Month = new SimpleDateFormat("MM");
       SimpleDateFormat sdf_Year = new SimpleDateFormat("yyyy");
       SimpleDateFormat sdf_final_Date = new SimpleDateFormat("MMMM yyyy");
       JLabel label = new JLabel();

       datepicker(){
          Smonth.setModel(new SpinnerDateModel(date, null, null, cal.MONTH));
          Smonth.setEditor(new JSpinner.DateEditor(Smonth, "MMMM"));
          Syear.setModel(new SpinnerDateModel(date, null, null, cal.YEAR));
          Syear.setEditor(new JSpinner.DateEditor(Syear, "yyyy"));

          Smonth.addChangeListener(new ChangeListener() {

                @Override
                public void stateChanged(ChangeEvent e) {
                   execute(); 

                }
            });

          Syear.addChangeListener(new ChangeListener() {

                @Override
                public void stateChanged(ChangeEvent e) {
                    execute();

                }
            });

          setLayout(new BorderLayout());
          add(Smonth, BorderLayout.WEST);
          add(label, BorderLayout.CENTER);
          add(Syear, BorderLayout.EAST);

          execute();
       }

           void execute(){


              cal.set(Integer.parseInt(sdf_Year.format(Syear.getValue())),
                  (Integer.parseInt(sdf_Month.format(Smonth.getValue())))-1,
                  1); 

              label.setText(sdf_final_Date.format(cal.getTime()));
           }

           public static void main(String[]args){
               new datepicker().setVisible(true);
           }    
    }

我完整的简单日期选择器

 package Feature.Other;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Calender extends JDialog{
    private Calendar cal=Calendar.getInstance();
    public  java.sql.Date initDate = new  java.sql.Date(cal.getTime().getTime());
    private  JPanel north = new JPanel();
    private JPanel center = new JPanel();
    private JLabel lFinalDate=new JLabel("tanggal");
    private JLabel lDate[]= new JLabel[49];
    private String day[]= {"SUN","MON","TUE","WED","THU","FRI","SAT"};
    private JSpinner smonth = new JSpinner();
    private JSpinner    sYear = new JSpinner();
    private DateFormat sdf = new SimpleDateFormat("dd MMMM yyyy");
    private DateFormat sdfM = new SimpleDateFormat("MM");
    private DateFormat sdfY = new SimpleDateFormat("yyyy");

    public Calender() {

        smonth.setModel(new SpinnerDateModel(initDate, null, null, cal.MONTH));
        smonth.setEditor(new JSpinner.DateEditor(smonth, "MMMM"));
        JFormattedTextField jft = ((JSpinner.DefaultEditor)smonth.getEditor()).getTextField();
        jft.setEditable(false);
        jft.setHorizontalAlignment(JLabel.LEFT);
        sYear.setModel(new SpinnerDateModel(initDate, null, null, cal.YEAR));
        sYear.setEditor(new JSpinner.DateEditor(sYear, "yyyy"));
        JFormattedTextField jft2 = ((JSpinner.DefaultEditor)sYear.getEditor()).getTextField();
        jft2.setEditable(false);

        smonth.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                dor(); 
            }
        });

        sYear.addChangeListener(new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
                dor();   
            }
        });

        setLayout(new BorderLayout());
        setSize(500,300);
        init();
    }

    private void init(){

        add(north, BorderLayout.NORTH);
        add(center, BorderLayout.CENTER);
        north.setLayout(new GridBagLayout());
        center.setLayout(new GridLayout(7,7));

        addComponen(sYear, 2,0,1,1, GridBagConstraints.CENTER, GridBagConstraints.BOTH);
        addComponen(smonth, 0,0,1,1, GridBagConstraints.CENTER, GridBagConstraints.BOTH);
        addComponen(lFinalDate,1,0,1,1, GridBagConstraints.CENTER, GridBagConstraints.BOTH);

        for (int i=0;  i<49;  i++ ){
          lDate[i]= new JLabel("");
          center.add(lDate[i]);

          if(i<7){
              lDate[i].setText(day[i]);
                }
        }
        dor();
    }

    private void addComponen(Component component,int gridx, int gridy, int gridwid, int gridheig,int achor, int fill){

        GridBagConstraints gc = new GridBagConstraints(gridx, gridy, gridwid, gridheig, 1.0, 1.0, achor,fill,new Insets(0, 0, 0, 0), 0, 0);
        north.add(component, gc);
    }

    private void dor(){
        cal.set(Integer.parseInt(sdfY.format(sYear.getValue())),
                Integer.parseInt(sdfM.format(smonth.getValue()))-1,
                1);
        lFinalDate.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lFinalDate.setText(sdf.format(cal.getTime()));
        int dayMax = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        int start = cal.get(Calendar.DAY_OF_WEEK);

        for (int i=7;  i<49;  i++ ){
          lDate[i].setText("");
          lDate[i].setForeground(Color.BLACK);
        }

        for (int a=6+start,b=1;b<=dayMax;a++,b++ ){
            final int selection = a;
            lDate[a].setText(""+b);
            lDate[a].addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent evt){
                    cal.set(Integer.parseInt(sdfY.format(sYear.getValue())),
                        Integer.parseInt(sdfM.format(smonth.getValue()))-1,
                        Integer.parseInt(lDate[selection].getText()));
                    initDate = new  java.sql.Date(cal.getTime().getTime());
                    for (int z=6;z<=42;z++){
                    lDate[z].setForeground(Color.BLACK);}
                    lDate[selection].setForeground(Color.blue);
                    lFinalDate.setText(sdf.format(initDate));    
                }
            });
        }
    }

    public static void main (String[]args){
        new Calender().setVisible(true);
    }

}

2 个答案:

答案 0 :(得分:2)

输入适当的参数类型,即:

  cal.set(Integer.parseInt(sdf_Year.format(Syear.getValue())), 
          Integer.parseInt(sdf_Month.format(Smonth.getValue())),
          1);

答案 1 :(得分:2)

  • 请阅读有关JSpinner

  • 的教程
  • 有关于JSpinnerSpinnerDateModel,inc的详细说明。有关教程的代码示例

修改

  • 没有理由解析任何东西,使用适当的SpinnerXxxModel,

  • 您可以测试,分割为三个JSpinner,如教程中所述,SpinnerDateModel的简单代码

import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;

public class TimeZoneSpinners {

    private final String[] zones = {"Asia/Tokyo", "Asia/Hong_Kong",
        "Asia/Calcutta", "Europe/Paris", "Europe/London",
        "America/New_York", "America/Los_Angeles"
    };
    private final JLabel[] labels = new JLabel[zones.length];
    private final SimpleDateFormat[] formats = new SimpleDateFormat[zones.length];
    private JSpinner spinner;
    private JSpinner spinnerDate;
    private JSpinner spinnerMonth;
    private JSpinner spinnerYear;
    private SpinnerDateModel model;
    private SimpleDateFormat format;
    private JPanel panel;
    private JFrame frame = new JFrame();

    public void makeUI() {
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        model = new SpinnerDateModel();
        model.setValue(date);
        spinner = new JSpinner(model);
        spinner.addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                Date date = (Date) ((JSpinner) e.getSource()).getValue();
                for (int i = 0; i < labels.length; i++) {
                    labels[i].setText(formats[i].format(date));
                }
            }
        });
        format = ((JSpinner.DateEditor) spinner.getEditor()).getFormat();
        format.setTimeZone(TimeZone.getTimeZone(zones[0]));
        format.applyPattern("yyyy-MM-dd HH:mm:ss");
        panel = new JPanel(new GridLayout(zones.length, 2, 10, 10));
        for (int i = 0; i < zones.length; i++) {
            formats[i] = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
            formats[i].setTimeZone(TimeZone.getTimeZone(zones[i]));
            JLabel label = new JLabel(zones[i]);
            labels[i] = new JLabel(formats[i].format(date));
            panel.add(label);
            panel.add(labels[i]);
        }
        frame.setLayout(new BorderLayout(10, 10));
        frame.add(spinner, BorderLayout.NORTH);
        frame.add(panel, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TimeZoneSpinners().makeUI();
            }
        });
    }
}