繁体   English   中英

Java:引用另一个 class 中的构造函数

[英]Java: Reference to constructor in another class

我正在尝试制作一个程序,该程序会自动从 a.json 文件中提取链接。 我是编程新手,我正在尝试组织代码,以便其他人能够更轻松地理解它。

我有一个名为 Gui 的构造函数,它在其中添加了一个关闭按钮和一个带有 awt 的文件浏览器。 为了组织项目,我想制作另一个 class 来提取链接,但我不知道如何在 Gui 类的构造函数中引用带有文件路径的 TextField。

我需要从另一个 class 中的 fe 获取文本。

我已经搜索了 web 几个小时,但找不到任何适合我的东西。

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 {
//create an inner class
class MyProcess
{
    MyProcess(String s)
    {
        System.out.println("do something with s="+s);
    }
}

public static void main(String args[])
{
    new Gui();
}

...

@Override
public void mouseClicked(MouseEvent e) {
    FileDialog fd = new FileDialog(gui, "file", FileDialog.LOAD);
    fd.setVisible(true);
    fe.setText(fd.getDirectory());
    //use the inner class as needed
    new MyProcess(fe.getText());
    }


控制台上可能的 output do something with s=D:\some_path\

请注意,内部 class 不是强制性的,也可以是外部 class。 这仅取决于您的设计。 也许将来您可以对图形界面进行一些研究: JavaFxSwing或者Eclipse Graphics Library Awt图书馆是最古老的图书馆。

你应该把你的类的引用,例如你的构造函数之外的文本,例如,

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 编程的基础知识,然后为自己定义更大的项目。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM