Swing可以使用SwingX中的JXDatePicker

解决方案 »

  1.   

    可以自己做一个:要源码的话告诉我邮箱
    用CSS样式表后的DateChooser,当然你还可以自己随心所欲的自定义CSS。用CSS样式表后的DateChooser,当然你还可以自己随心所欲的自定义CSS。或者使用别人做好的
      

  2.   

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.sql.Date;
    import java.util.Calendar;import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;class MainFrame extends JFrame {
    private static final long serialVersionUID = 1L;
    JPanel panel = new JPanel(new BorderLayout());
    JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel(new GridLayout(7, 7));
    JLabel[] label = new JLabel[49];
    JLabel y_label = new JLabel("年份");
    JLabel m_label = new JLabel("月份");
    JComboBox com1 = new JComboBox();
    JComboBox com2 = new JComboBox();
    int re_year, re_month;
    int x_size, y_size;
    String year_num;
    Calendar now = Calendar.getInstance(); // 实例化Calendar MainFrame() {
    super("万年历");
    setSize(500, 500);
    this.setLocationRelativeTo(null);
    panel1.add(y_label);
    panel1.add(com1);
    panel1.add(m_label);
    panel1.add(com2);
    for (int i = 0; i < 49; i++) {
    label[i] = new JLabel("", JLabel.CENTER);// 将显示的字符设置为居中
    panel2.add(label[i]);
    }
    panel.add(panel1, "North");
    panel.add(panel2);
    panel1.setBackground(Color.green);
    panel2.setBackground(Color.pink);
    Init();
    com1.addActionListener(new MyListener());
    com2.addActionListener(new MyListener()); this.add(panel);
    this.setResizable(false);
    this.setVisible(true);
    } class MyListener implements ActionListener {
    public void actionPerformed(ActionEvent arg0) {
    int c_year, c_month, c_week;
    c_year = Integer.parseInt(com1.getSelectedItem().toString()); // 得到当前所选年份
    c_month = Integer.parseInt(com2.getSelectedItem().toString()) - 1; // 得到当前月份,并减1,计算机中的月为0-11
    c_week = use(c_year, c_month); // 调用函数use,得到星期几
    Resetday(c_week, c_year, c_month); // 调用函数Resetday
    }
    } public void Init() {
    int year, month_num, first_day_num;
    String log[] = { "日", "一", "二", "三", "四", "五", "六" };
    for (int i = 0; i < 7; i++) {
    label[i].setText(log[i]);
    }
    for (int i = 0; i < 49; i = i + 7) {
    label[i].setForeground(Color.red); // 将星期日的日期设置为红色
    }
    for (int i = 6; i < 49; i = i + 7) {
    label[i].setForeground(Color.red);// 将星期六的日期设置为绿色
    }
    for (int i = 1; i < 2600; i++) {
    com1.addItem("" + i);
    }
    for (int i = 1; i < 13; i++) {
    com2.addItem("" + i);
    }
    month_num = (int) (now.get(Calendar.MONTH)); // 得到当前时间的月份
    year = (int) (now.get(Calendar.YEAR)); // 得到当前时间的年份
    com1.setSelectedIndex(year - 1); // 设置下拉列表显示为当前年
    com2.setSelectedIndex(month_num); // 设置下拉列表显示为当前月
    first_day_num = use(year, month_num);
    Resetday(first_day_num, year, month_num);
    } public int use(int reyear, int remonth) {
    int week_num;
    now.set(reyear, remonth, 1); // 设置时间为所要查询的年月的第一天
    week_num = (int) (now.get(Calendar.DAY_OF_WEEK));// 得到第一天的星期
    return week_num;
    } @SuppressWarnings("deprecation")
    public void Resetday(int week_log, int year_log, int month_log) {
    int month_day_score=0; // 存储月份的天数
    int count=1; Date date = new Date(year_log, month_log + 1, 1); // now
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.add(Calendar.MONTH, -1); // 前个月
    month_day_score = cal.getActualMaximum(Calendar.DAY_OF_MONTH);// 最后一天 for (int i = 7; i < 49; i++) { // 初始化标签
    label[i].setText("");
    }
    week_log = week_log + 6; // 将星期数加6,使显示正确
    for (int i = week_log; i < month_day_score+week_log; i++, count++) {
    label[i].setText(count + "");
    }
    } public static void main(String[] args) {
    new MainFrame();
    }
    }
      

  3.   

    [email protected]谢谢你,希望带点注释
      

  4.   

    [email protected]谢谢你,希望带点注释
    由DateChooser.java(继承拓展控件Control + DateChooserSkin.java(定义皮肤)构成。提供了2种CSS样式表选择以及一个Test使用DateChooser的样例程序。分别如下:背景图片(位于images文件夹)package datechooser;import javafx.application.Application;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.layout.StackPane;
    import javafx.stage.Stage;
    import javafx.stage.WindowEvent;
    public class TestApplication extends Application {    /**
         @param args the command line arguments
         */
        public static void main(String[] args) {
            launch(args);
        }
        
        @Override
        public void start(final Stage primaryStage) {
            primaryStage.setTitle("Hello World!");
            StackPane root = new StackPane();
            final DateChooser dateChooser = new DateChooser();
            root.getChildren().add(dateChooser);
            Scene scene = new Scene(root, 300, 250);  
            scene.getStylesheets().add(TestApplication.class.getResource("lcd.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.setOnHiding(new EventHandler<WindowEvent>() {                    public void handle(WindowEvent event) {
                            System.out.println("date " + dateChooser.getDate());
                        }
                    });
            primaryStage.show();
        }
    }
    package datechooser;import java.util.Date;
    import javafx.scene.control.Control;public class DateChooser extends Control{    private static final String DEFAULT_STYLE_CLASS = "date-chooser";
        private Date date;    public DateChooser(Date preset) {
            getStyleClass().setAll(DEFAULT_STYLE_CLASS);
            this.date = preset;
        }    public DateChooser() {
            this(new Date(System.currentTimeMillis()));
        }    @Override
        protected String getUserAgentStylesheet() {
            return "datechooser/calendar.css";
        }    public Date getDate() {
            return date;
        }
    }
      

  5.   

    package datechooser;import com.sun.javafx.scene.control.behavior.BehaviorBase;
    import com.sun.javafx.scene.control.skin.SkinBase;
    import java.text.DateFormatSymbols;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.geometry.HPos;
    import javafx.geometry.Insets;
    import javafx.geometry.Pos;
    import javafx.geometry.VPos;
    import javafx.scene.Node;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.layout.*;public class DateChooserSkin extends SkinBase<DateChooser, BehaviorBase<DateChooser>> {    private final Date date;
        private final Label month;
        private final BorderPane content;
        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMMM yyyy");    private static class CalendarCell extends StackPane {        private final Date date;        public CalendarCell(Date day, String text) {
                this.date = day;
                Label label = new Label(text);
                getChildren().add(label);
            }        public Date getDate() {
                return date;
            }
        }    public DateChooserSkin(DateChooser dateChooser) {
            super(dateChooser, new BehaviorBase<DateChooser>(dateChooser));
            // this date is the selected date
            date = dateChooser.getDate();
            final DatePickerPane calendarPane = new DatePickerPane(date);
            month = new Label(simpleDateFormat.format(calendarPane.getShownMonth()));
            HBox hbox = new HBox();        // create the navigation Buttons
            Button yearBack = new Button("<<");
            yearBack.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {            @Override
                public void handle(ActionEvent event) {
                    calendarPane.forward(-12);            }
            });
            Button monthBack = new Button("<");
            monthBack.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {            @Override
                public void handle(ActionEvent event) {
                    calendarPane.forward(-1);
                }
            });
            Button monthForward = new Button(">");
            monthForward.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {            @Override
                public void handle(ActionEvent event) {
                    calendarPane.forward(1);
                }
            });
            Button yearForward = new Button(">>");
            yearForward.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {            @Override
                public void handle(ActionEvent event) {
                    calendarPane.forward(12);
                }
            });        // center the label and make it grab all free space
            HBox.setHgrow(month, Priority.ALWAYS);
            month.setMaxWidth(Double.MAX_VALUE);
            month.setAlignment(Pos.CENTER);
            hbox.getChildren().addAll(yearBack, monthBack, month, monthForward, yearForward);        // use a BorderPane to Layout the view
            content = new BorderPane();
            getChildren().add(content);
            content.setTop(hbox);
            content.setCenter(calendarPane);
        }    /**     @author eppleton
         */
        class DatePickerPane extends Region {        private final Date selectedDate;
            private final Calendar cal;
            private CalendarCell selectedDayCell;
            // this is used to format the day cells
            private final SimpleDateFormat sdf = new SimpleDateFormat("d");
            // empty cell header of weak-of-year row
            private final CalendarCell woyCell = new CalendarCell(new Date(), "");
            private int rows, columns;//default        public DatePickerPane(Date date) {
                setPrefSize(300, 300);
                woyCell.getStyleClass().add("week-of-year-cell");
                setPadding(new Insets(5, 0, 5, 0));
                this.columns = 7;
                this.rows = 5;            // use a copy of Date, because it's mutable
                // we'll helperDate it through the month
                cal = Calendar.getInstance();
                Date helperDate = new Date(date.getTime());
                cal.setTime(helperDate);            // the selectedDate is the date we will change, when a date is picked
                selectedDate = date;
                refresh();
            }        /**
             Move forward the specified number of Months, move backward by using
             negative numbers         @param i
             */
            public void forward(int i) {            cal.add(Calendar.MONTH, i);
                month.setText(simpleDateFormat.format(cal.getTime()));
                refresh();
            }        private void refresh() {
                super.getChildren().clear();
                this.rows = 5; // most of the time 5 rows are ok
                // save a copy to reset the date after our loop
                Date copy = new Date(cal.getTime().getTime());            // empty cell header of weak-of-year row
                super.getChildren().add(woyCell);            // Display a styleable row of localized weekday symbols 
                DateFormatSymbols symbols = new DateFormatSymbols();
                String[] dayNames = symbols.getShortWeekdays();            // @TODO use static constants to access weekdays, I suspect we 
                // get problems with localization otherwise ( Day 1 = Sunday/ Monday in
                // different timezones
                for (int i = 1; i < 8; i++) { // array starts with an empty field
                    CalendarCell calendarCell = new CalendarCell(cal.getTime(), dayNames[i]);
                    calendarCell.getStyleClass().add("weekday-cell");
                    super.getChildren().add(calendarCell);
                }            // find out which month we're displaying
                cal.set(Calendar.DAY_OF_MONTH, 1);
                final int month = cal.get(Calendar.MONTH);            int weekday = cal.get(Calendar.DAY_OF_WEEK);            // if the first day is a sunday we need to rewind 7 days otherwise the 
                // code below would only start with the second week. There might be 
                // better ways of doing this...
                if (weekday != Calendar.SUNDAY) {
                    // it might be possible, that we need to add a row at the end as well...                Calendar check = Calendar.getInstance();
                    check.setTime(new Date(cal.getTime().getTime()));
                    int lastDate = check.getActualMaximum(Calendar.DATE);
                    check.set(Calendar.DATE, lastDate);
                    if ((lastDate + weekday) > 36) {
                        rows = 6;
                    }                cal.add(Calendar.DATE, -7);            }
                cal.set(Calendar.DAY_OF_WEEK, 1);            // used to identify and style the cell with the selected date;
                Calendar testSelected = Calendar.getInstance();
                testSelected.setTime(selectedDate);            for (int i = 0; i < (rows); i++) {                // first column shows the week of year
                    CalendarCell calendarCell = new CalendarCell(cal.getTime(), "" + cal.get(Calendar.WEEK_OF_YEAR));
                    calendarCell.getStyleClass().add("week-of-year-cell");
                    super.getChildren().add(calendarCell);                // loop through current week
                    for (int j = 0; j < columns; j++) {
                        String formatted = sdf.format(cal.getTime());
                        final CalendarCell dayCell = new CalendarCell(cal.getTime(), formatted);
                        dayCell.getStyleClass().add("calendar-cell");
                        if (cal.get(Calendar.MONTH) != month) {
                            dayCell.getStyleClass().add("calendar-cell-inactive");
                        } else {
                            if (isSameDay(testSelected, cal)) {
                                dayCell.getStyleClass().add("calendar-cell-selected");
                                selectedDayCell = dayCell;
                            }
                            if (isToday(cal)) {
                                dayCell.getStyleClass().add("calendar-cell-today");
                            }                    }
                        dayCell.setOnMouseClicked(new EventHandler<MouseEvent>() {                        @Override
                            public void handle(MouseEvent arg0) {
                                if (selectedDayCell != null) {
                                 //   selectedDayCell.getStyleClass().add("calendar-cell");
                                    selectedDayCell.getStyleClass().remove("calendar-cell-selected");
                                }
                                selectedDate.setTime(dayCell.getDate().getTime());
                           //     dayCell.getStyleClass().remove("calendar-cell");
                                dayCell.getStyleClass().add("calendar-cell-selected");
                                selectedDayCell = dayCell;
                                Calendar checkMonth = Calendar.getInstance();
                                checkMonth.setTime(dayCell.getDate());                            if (checkMonth.get(Calendar.MONTH) != month) {
                                    forward(checkMonth.get(Calendar.MONTH) - month);
                                }
                            }
                        });                    // grow the hovered cell in size  
                        dayCell.setOnMouseEntered(new EventHandler<MouseEvent>() {                        @Override
                            public void handle(MouseEvent e) {
                                dayCell.setScaleX(1.1);
                                dayCell.setScaleY(1.1);
                            }
                        });
      

  6.   


                        dayCell.setOnMouseExited(new EventHandler<MouseEvent>() {                        @Override
                            public void handle(MouseEvent e) {
                                dayCell.setScaleX(1);
                                dayCell.setScaleY(1);
                            }
                        });                    super.getChildren().add(dayCell);
                        cal.add(Calendar.DATE, 1);  // number of days to add
                    }
                }
                cal.setTime(copy);
            }        /**
             Overriden, don't add Children directly         @return unmodifieable List
             */
            @Override
            protected ObservableList<Node> getChildren() {
                return FXCollections.unmodifiableObservableList(super.getChildren());
            }        /**
             get the current month our calendar displays. Should always give you the
             correct one, even if some days of other mnths are also displayed         @return
             */
            public Date getShownMonth() {
                return cal.getTime();
            }        @Override
            protected void layoutChildren() {
                ObservableList<Node> children = getChildren();
                double width = getWidth();
                double height = getHeight();            double cellWidth = (width / (columns + 1));
                double cellHeight = height / (rows + 1);            for (int i = 0; i < (rows + 1); i++) {
                    for (int j = 0; j < (columns + 1); j++) {
                        if (children.size() <= ((i * (columns + 1)) + j)) {
                            break;
                        }
                        Node get = children.get((i * (columns + 1)) + j);
                        layoutInArea(get, j * cellWidth, i * cellHeight, cellWidth, cellHeight, 0.0d, HPos.LEFT, VPos.TOP);
                    }            }
            }
        }
        // utility methods    private static boolean isSameDay(Calendar cal1, Calendar cal2) {
            if (cal1 == null || cal2 == null) {
                throw new IllegalArgumentException("The dates must not be null");
            }
            return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA)
                    && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
                    && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
        }    private static boolean isToday(Calendar cal) {
            return isSameDay(cal, Calendar.getInstance());
        }
    }
    .date-chooser {
        -fx-skin: "datechooser.DateChooserSkin";
    }.weekday-cell { 
        -fx-background-color: lightgray;
        -fx-background-radius: 5 5 5 5;
        -fx-background-insets: 2 2 2 2 ;
        -fx-text-fill: darkgray;
        -fx-text-alignment: left;
        -fx-font: 12pt "Tahoma Bold";
    }.week-of-year-cell { 
        -fx-background-color: lightgray;
        -fx-background-radius: 5 5 5 5;
        -fx-background-insets: 2 2 2 2 ;
        -fx-text-fill: white;
        -fx-text-alignment: left;
        -fx-font: 12pt "Tahoma Bold";
    }.calendar-cell { 
        -fx-background-color: skyblue, derive(skyblue, 25%), derive(skyblue, 50%), derive(skyblue, 75%);
        -fx-background-radius: 5 5 5 5;
        -fx-background-insets: 2 2 2 2 ;
        -fx-text-fill: skyblue;
        -fx-text-alignment: left;
        -fx-font: 12pt "Tahoma Bold";
    }.calendar-cell:hover { 
        -fx-background-color: skyblue; 
        -fx-text-fill: white;   
    }.calendar-cell:pressed { 
        -fx-background-color: darkblue;  
        -fx-text-fill: green;   
    }.calendar-cell-selected { 
        -fx-background-color: darkblue;  
        -fx-text-fill: white;   
    }.calendar-cell-inactive { 
        -fx-background-color: derive(lightgray, 75%);
        -fx-text-fill: darkgray;
    }.calendar-cell-today { 
        -fx-background-color: yellow;  
        -fx-text-fill: skyblue;
    }.date-chooser {
        -fx-background-color:linear-gradient(white,#DDDDDD);
        -fx-background-image: url("images/background.png");
        -fx-background-repeat: no-repeat;
        -fx-background-position: left bottom;
    }.label {    
         -fx-effect: dropshadow(two-pass-box , darkgray, 10, 0.0 , 4, 5);
         
    }.calendar-cell { 
        -fx-background-color: rgba(255,255,255,0.0);
        -fx-background-radius: 15 15 15 15;
        -fx-background-insets: 6 6 6 6 ;
        -fx-text-fill: rgba(0,0,0,0.7);
        -fx-font: 16pt Arial;
    }.calendar-cell:hover { 
        -fx-background-color: rgba(135,206,235,0.7);
        -fx-text-fill: white;   
    }.calendar-cell:pressed { 
        -fx-background-color: rgba(135,186,215,0.7);
        -fx-text-fill: white;   
    }.calendar-cell-selected { 
        -fx-background-color: rgba(105,176,195,0.7);
        -fx-text-fill: white;   
    }.calendar-cell-today { 
        -fx-background-color: rgba(155,155,19,0.7);
        -fx-text-fill: white;
    }.calendar-cell-inactive { 
        -fx-text-fill: darkgray;
    }.weekday-cell { 
        -fx-background-color: rgba(255,255,255,0.0);
        -fx-text-fill: black;
        -fx-font: italic bold 16pt Arial;
    }.week-of-year-cell { 
        -fx-background-color: rgba(255,255,255,0.0);
        -fx-text-fill: black;
        -fx-font: italic bold 16pt Arial;
    }.button{
        -fx-effect: dropshadow(two-pass-box , darkgray, 10, 0.0 , 4, 5);
        -fx-background-color: rgba(205,205,205,0.7);
        -fx-background-radius: 15 15 15 15;
        -fx-background-insets: 2 2 2 2 ;
    }.button:pressed{
        -fx-background-color: rgba(180,180,180,0.7);
    }.button:hover{
        -fx-background-color: rgba(235,235,235,0.7);
    }.button:focused{
        -fx-background-color: rgba(205,205,205,0.7);
      
    }
      

  7.   

    你好我想问一下在javafx project中的类添加这个com.sun.javafx.scene.control.skin.SkinBase引用失败,在网上也没有找到相关的包。具体是什么原因