如何在 Java 中创建日期选择器?
要创建日期选择器,请使用 SpinnerDateModel 类。在其中设置日期格式 −
Date today = new Date(); JSpinner spinner2 = new JSpinner(new SpinnerDateModel(today, null, null, Calendar.MONTH)); JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner2, "dd/MM/yy"); spinner2.setEditor(editor);
上面,我们设置了以下日期格式 −
dd/MM/yy
以下是一个在 Java 中创建日期选择器的示例 −
示例
package my; import java.awt.GridBagLayout; import java.util.Calendar; import java.util.Date; import javax.swing.*; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame("Spinner Demo"); JPanel panel = new JPanel(); JLabel label = new JLabel("Exam No."); JLabel label2 = new JLabel(" Appeared On"); panel.setLayout(new GridBagLayout()); int min = 0; int max = 10; int step = 1; int i = 5; SpinnerModel value = new SpinnerNumberModel(i, min, max, step); JSpinner spinner = new JSpinner(value); spinner.setBounds(50, 80, 70, 100); Date today = new Date(); JSpinner spinner2 = new JSpinner(new SpinnerDateModel(today, null, null, Calendar.MONTH)); JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner2, "dd/MM/yy"); spinner2.setEditor(editor); panel.add(label); panel.add(spinner); panel.add(label2); panel.add(spinner2); frame.add(panel); frame.setSize(550,300); frame.setVisible(true); } }
输出
广告