我正在为我的一个类编写原始地址簿的代码,并且要求我们为地址簿本身使用一个类,然后使用另一个类来放入新条目。我理解这一点,但是当我调用用于输入新联系人的类方法时,我想更改 GUI。我正在使用 JFrame,因此对于我的 GUI 基础,我使用 contentPane
。在我的第一个类中,我使用基本 GUI 创建了 contentPane
:
public class Address extends JFrame implements ActionListener
{
Container contentPane;
public Address()
{
super();
contentPane = getContentPane();
contentPane.setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Address Book");
setSize(775,775);
setLocation(0,0);
setBackground(Color.BLUE);
}
}
现在在我的第二个类(输入类)中,我想使用 contentPane.removeAll()
清除 contentPane
。
class Entries
{
public void newContact()
{
contentPane.removeAll();
}
}
不幸的是,我的类 Entries 中没有任何内容可以识别 contentPane
以及我试图修改的其他变量。是否有一种特殊的方法来命名 Address 类中的 contentPane
和其他变量,以便它们可以在 Entries 中使用,或者我是否需要重新创建变量?
最佳答案
当您创建 Entries
对象时,您需要为其提供对 Address
对象的引用,以便可以使用其变量。我不确定你的程序布局是如何设置的,但如果 Entries
是在 Address
中创建的,你会调用 Entries entry = new Entry(this);
或者如果它来自两个类的父类,您需要设置变量...
Address address = new Address();
Entries entry = new Entry(address);
如何在条目中访问它的代码:
class Entries
{
private Address reference;
public Entries(Address reference) {
this.reference = reference;
}
public void newContact()
{
reference.contentPane.removeAll();
}
}
关于java - 从一个类调用另一个类的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14524431/