java - 自动填充组合框系列 - Java

标签 java date jcombobox autofill

我正在编写一个简单的程序;该程序的一部分是一系列组合框,我在其中输入了月份(alpha)、天(数字)和年(数字)的字符串。我希望以某种方式让 Java 以月、日和年的形式提取日期,然后根据系统时钟自动填充这些组合框,其中包含正确的日期。

这是我的一些代码:

public static final String[] MONTHS = {"January", "February", "March", "April", "May", "June",
                                       "July", "August", "September", "October", "November",
                                       "December"};
public static final String[] DAYS = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", 
                                 "12", "13", "14", "15", "16", "17", "18", "19", "20", 
                                 "21", "22", "23", "24", "25", "26", "27", "28", "29", 
                                 "30", "31"};
public static final String[] YEARS = {"2015", "2014", "2013", "2012", "2011", "2010"};

Note to FORUMS: THIS ISN'T ALL THE CODE. I'VE JUST PROVIDED INFORMATION NECESSARY FOR THE QUESTION.

JLabel start = new JLabel("Start Date:");
if (shouldWeightX) {
c.weightx = .5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
pane.add(start, c);

JComboBox MonthLong = new JComboBox();
if (shouldWeightX) {
    c.weightx = 0;
    }
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 1;
for(int i=0; i<MONTHS.length;i++) {
        MonthLong.addItem(MONTHS[i]);
    }
pane.add(MonthLong, c);

JComboBox DayLong = new JComboBox();
if (shouldWeightX) {
    c.weightx = 1.0;
    }
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridy = 1;
c.gridwidth = 1;
for(int i=0; i<DAYS.length;i++) {
    DayLong.addItem(DAYS[i]);
}
pane.add(DayLong, c);

JComboBox YearLong = new JComboBox();
if (shouldWeightX) {
    c.weightx = 1.0;
    }
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 3;
c.gridy = 1;
c.gridwidth = 1;
for(int i=0; i<YEARS.length;i++) {
    YearLong.addItem(YEARS[i]);
}
YearLong.setSelectedItem("2013");
pane.add(YearLong, c);

提前致谢。

最佳答案

您应该使用 java.util.Calendar 类获取当前时间部分。

Calendar now = Calendar.getInstance();
// months start with 0 
System.out.println("Year is: " + now.get(Calendar.YEAR));   
System.out.println("Month is: " + (now.get(Calendar.MONTH) + 1));
System.out.println("Date is: " + now.get(Calendar.DATE));

然后您可以在初始化步骤中在组合框上设置SelectedIndex。

还请记住,您不必使用 for 循环将这些字符串添加到组合框。就试试吧。

JComboBox<String> MonthLong = new JComboBox<String>(MONTHS);

关于java - 自动填充组合框系列 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15690161/

相关文章:

java - 即使添加到构建路径并清理后也无法解决导入问题

java - 输入文本只接受数字

Java Gson .add 函数不采用 String 参数(maven 项目)

使用 to_date 的 Oracle 日期比较不起作用

java - 如何使用下拉菜单的结果创建字符串?

java - 从组合框中选择时,JTable 不刷新

sqlite - 仅控制 SQLite 属性的输入为日期格式。

java - 从文本文件填充 JCombobox

java - 在java中为组合框分配键

Java - 验证给定的字符串是否代表日期,即 "YYYY-MM-DD"?