2012-07-19 33 views
1

我正在嘗試創建一個對象並將其添加到我創建的數組中作爲我構建的參數GUI對象。出於某種原因,我一直收到TheDates無法解析爲變量使用事件處理程序更改對象參數

對象正在建設中:

public static void main(String[] args) 
{ 
    DateDriver myDateFrame = new DateDriver(); 
} 

//Constructor 
public DateDriver() 
{ 
    outputFrame = new JFrame(); 
    outputFrame.setSize(600, 500); 
    outputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    String command; 
    Date [] theDates = new Date[100]; //this is the array I am having issues with 
    int month, day, year; 

    ... 
} 

這是我與theDates的問題是:

public void actionPerformed(ActionEvent e) 
{ //The meat and Potatoes 
    if (e.getSource() == arg3Ctor) 
    { 
     JOptionPane.showMessageDialog(null, "3 arg Constructor got it"); 
     int month = Integer.parseInt(monthField.getText()); 
     int day = Integer.parseInt(dayField.getText()); 
     int year = Integer.parseInt(yearField.getText()); 
     theDates[getIndex()] = new Date(month, day, year);//here is the actual issue 
    } 
} 

我不知道如果我思前想還是什麼,我已經試過使陣列靜態,公衆,等我也嘗試實施它作爲myDayeFrame.theDates

任何指導不勝感激

回答

2

您可能有一個範圍問題。日期在構造函數中聲明,只在構造函數中可見。一個可能的解決方案:將其聲明爲類字段。確保在構造函數中初始化它,但是如果它在類中聲明,則它在類中可見。

+0

+1您可以通過14秒打我。 – 2012-07-19 04:07:56

+1

非常感謝!我非常感謝幫助,我從來沒有想過將參數初始化爲類字段。我是這樣做的按鈕,但它只是沒有點擊我。非常感謝你,我會提供這個技巧給我的同班同學,他們有同樣的問題。 – 2012-07-19 04:34:25

+0

@Dustin:很高興我們能幫上忙。祝你好運! – 2012-07-19 04:36:08

2

您正在將theDates定義爲構造函數中的局部變量,因此它的作用域在構造函數中是有限的。取而代之的是,它聲明爲類的字段:

private Data[] theDates; 

// ... 

    public DateDriver() 
    { 
     theDates = new Date[100]; 
     // ... 
    } 
+0

GMTA。 1+ upvote – 2012-07-19 04:06:13

1

1.您已定義theDates,這是內部構造的Array對象參考變量,所以具有其構造本身內其範圍。

2.你應該在類範圍聲明theDates,所以它會貫穿類中是可見的。

如果你使用的收集,而不是陣列,去ArrayList的

例如,它會更好:

public class DateDriver { 

    private ArrayList<Date> theDates; 

    public DateDriver() { 
     theDates = new ArrayList<Date>(); 
    } 
} 
+0

我希望我可以使用ArrayList,但老師對他的要求非常嚴格。我很欣賞投入,你非常清楚和簡潔。 – 2012-07-19 04:41:24

相關問題