Java:对另一个类的构造函数的引用

问题描述 投票:0回答:2

我正在尝试制作一个程序,该程序会自动从.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);
    }

}
java constructor reference awt
2个回答
0
投票

您应该将您的参考文献放在您的课​​程中,例如构造函数之外的文本,例如]

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;
}
}

我建议您学习Java编程的基础知识,然后为自己定义更大的项目。


0
投票

可以尝试以下更新

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());
    }

控制台上可能的输出do something with s=D:\some_path\请注意,内部类不是强制性的,也可以是外部类。这仅取决于您的设计。也许将来在图形界面上您也可以进行以下研究:JavaFxSwingEclipse Graphics LibraryAwt图书馆是最古老的图书馆。

© www.soinside.com 2019 - 2024. All rights reserved.