2012-07-19 27 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

相关问题