我的对话框有什么问题,我应该如何从不同的类和单独的.java文件更改数组列表?



我正在尝试编写一个GUI程序,该程序将导入一个文本文件,读取其内容并将其放入ArrayList中。

我在一个单独的.java文件中编写面板,该文件包含导入按钮并执行导入功能,而Arraylist在不同的.java(主方法)文件上。

我应该如何让ActionListener从不同的类/.java文件读取文件内容并将其导入ArrayList?

我的导入对话框alos导致错误,它有什么问题?该代码在CLI中运行良好,但在GUI程序中则不然。

这是GUI Frame的主要方法,它将从不同的.java文件添加面板:

public class FrameGUI 
{
    public static void main(String[] args) throws Exception
    {
        //Creates ArrayList and initiating JFrame
        ArrayList<String> stringFile = new ArrayList<String>();
        JFrame frame = new JFrame("Title");

        *//Rest of the following codes here*        

    }  //---End of Main Method---

} ---End of the First .java file

这是第二个.java文件,其中包含带有导入按钮的面板,并执行操作,读取.txt文件的内容并将其导入arraylist:

public class ImportPanel extends JPanel
{
    private JButton importButton;
    public ImportPanel(ArrayList<String> StringFile)
    {
    //Setting up JButton and link it to inner class of
    //ActionListener
    importButton = new JButton("Import Data");
    importButton.addActionListener(new importListener());

    *//***Adding the button into panel, set background color and panel size*
}  //---End of main method---

    //Private inner class:
    private class importListener implements ActionListener
    {
        public void actionPerformed (ActionEvent event)
        {
            //---Import Function---
            //The following statement will ask the user for input first 
            //BEFORE it displays title and JFrame
            //Setting the file type, showing the dialog box:
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES",
                    "txt","text"); //only allows user to import .txt files
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(null);

            //Execute the following and import data
            //if the file type match:
            Scanner fileScan;
            String stringAdd;
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File inputFile = chooser.getSelectedFile();
                fileScan = new Scanner(inputFile);
                //Scan the first line as title:
                //-disable-frame = new JFrame (fileScan.nextLine());

                //Parsing the data into Arraylist
                while (fileScan.hasNext())
                {
                    stringAdd = fileScan.nextLine();
                    StringFile.add(new String(stringAdd));
                } }  //End of the if statement- 
        }

    }  //---End of private inner class---

}  //End of the second .java file

在询问问题之前,我已经尝试过搜索,我知道为了改变不同类上的变量,我们需要添加一个叫做引用的东西。但在这种情况下,当类位于两个不同的.java文件而不是一个文件上时,我不知道如何添加以及在哪里添加。

ImportPanel类中,如何在importListener内部类中使用StringFile ArrayList对象?这里StringFileImportPanel()构造函数的本地对象。检查此项以了解java中的pass-by-reference。在您的情况下,我更喜欢在一个类中使用单个public static ArrayList<String> StringFile;对象,并在所有其他类中使用它。

最新更新