2013-03-28 4 views
0

간단한 프로그램을 작성하고 있습니다. 이 프로그램의 한 부분은 Comboboxes 시리즈로, 달 (알파), 일 (숫자) 및 년 (숫자)의 문자열을 제공합니다. 필자는 Java가 달, 일 및 연도의 관점에서 날짜를 가져온 다음 시스템 시계에 따라 올바른 날짜로 자동 채우기를 수행하도록하고 싶습니다. 사전에자동 채우기 ComboBox 시리즈 - 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); 

감사 :

여기 내 코드의 일부이다.

답변

0

이 코드는 테스트하지 않았습니다.

Calendar now = Calendar.getInstance(); 
    int month = now.get(Calendar.MONTH); 
    int day = now.get(Calendar.DAY_OF_MONTH); 
    int year = now.get(Calendar.YEAR); 

    MonthLong.setSelectedIndex(month); 
    DayLong.setSelectedItem(Integer.toString(day)); 
    YearLong.setSelectedItem(Integer.toString(year)); 

Java에서 변수는 대개 소문자로 시작합니다.

+0

이것은 효과가 있습니다. 고맙습니다. 또한, 나는 변수에 대한 소문자를 알고 있고, 다른 사람을위한 코드를 편집하고 있는데,이 질문에서 나는 그것이 "광산"이라고 말했다. 와! 다시 한번 감사드립니다. – user2221125

1

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);