【发布时间】:2014-09-01 21:14:58
【问题描述】:
我的类中有一个名为 addNewProduct(String name) 的主方法。 main 创建DesktopGUI 的副本,该对象构成框架和所有组件。我想有一种方法可以从DesktopGUI 调用主类中的方法。
主类(这是有问题的代码行。这不是我的代码的完整表示。代码行也可能与它们在我的实际应用程序中的顺序不同。)
public List<Product> productList;
public void addNewProduct(String name){
Product product = new Product();
product.setName(name);
productList.add(product);
}
DesktopGUI gui = new DesktopGUI();
frame = gui.getFrame();
在DesktopGUI 的构造函数中,它创建并显示框架。
在我的一段代码中
SaveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
System.out.println("Save Button Pressed");
System.out.println("Name: "+(String)fileNameField.getText());
/*the addNewProduct() is located in the class for main*/
addNewProduct((String)fileNameField.getText());
}
});
如果类是静态的,我可以调用它,但类 productList 的大小始终为零。
举个简单的例子
public class Foo {
public List<Product> productList;
public static void main(String[] args) {
A a = new A();
}
public void addNewProduct(String name){
Product product = new Product();
product.setName(name);
productList.add(product);
}
}
class A {
SaveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
foo.addNewProduct("Hello World");
}
});
}
【问题讨论】: