java - Java:引用另一个类中的构造函数
问题描述
我正在尝试制作一个程序,该程序会自动从 .json 文件中提取链接。我是编程新手,我正在尝试组织代码,以便其他人能够更轻松地理解它。
我有一个名为 Gui 的构造函数,它在其中添加了一个关闭按钮和一个带有 awt 的文件资源管理器。为了组织项目,我想制作另一个类来提取链接,但我不知道如何在 Gui 类的构造函数中引用带有文件路径的 TextField。
我需要从另一个班级的 fe 获取文本。
我已经在网上搜索了几个小时,但找不到任何适合我的东西。
public class Gui extends Frame {
public Gui() {
Frame gui = new Frame(Strings.name);
// add "close" button
Button cls = new Button(Strings.close);
cls.setBounds(30, 30, 100, 30);
gui.add(cls);
cls.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// file explorer
TextField fe = new TextField(Strings.file);
fe.setBounds(50,100, 200,30);
fe.setLocation(75, 75);
gui.add(fe);
fe.addMouseListener(new MouseListener() {
public void mouseReleased(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseClicked(MouseEvent e) {
FileDialog fd = new FileDialog(gui, Strings.cfile, FileDialog.LOAD);
fd.setVisible(true);
fe.setText(fd.getDirectory());
}
});
// make application work
gui.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
gui.setSize(1200, 900);
gui.setLayout(null);
gui.setVisible(true);
}
}
解决方案
你应该把你的类的引用,例如你的构造函数之外的文本,例如,
public class Gui extends Frame {
// your reference
private TextField text;
Gui() {
// now instantiate your textField
text = new TextField();
}
// getter method that returns your textField
public TextField getTextField() {
return text;
}
}
然后你可以从你的 gui 中获取你的文本。
Gui gui = new Gui();
TextField field =gui.getTextField();
我建议学习 Java 编程的基础知识,然后为自己定义更大的项目。