选择一个文件,通读它,并将其内容附加到两个链接列表中

时间:2019-04-30 06:06:55

标签: java jframe

我当前正在编写一个程序,该程序应读取文件,逐行浏览文件,使用StringTokenizer分隔Make(字符串),Model(字符串),Year(整数)和Mileage(整数),将这些值存储在Car对象(按此Car(Make,Model,Year,Mileage)的顺序)中,然后将其作为节点添加到2个链接列表中(其中一个按Make排序,另一个按')。我成功完成了所有这些工作,并且一切正常,但是,我现在要负责在我现有的程序(actionListener,JMenuItem,JMenuBar,JMenu等)中实施事件驱动的编程。在我声明一个名为“ file”的String对象并将其设置为等于我们应该从主类中的(cars.txt)读取的文件之前,但是现在我必须向CarGUI添加文件菜单打开文件读取。 它当前正在运行,但在GUI中未显示任何内容。我所做的一项更改是使readFile方法将File作为参数而不是String接受,以使其与 FileMenuHandler 类中的内容兼容。

CarGUI类 这是创建JFrame并存在readFile方法的类。这是链接列表(SortedCarList和UnSortedCarList)被附加到JTextAreas的地方。

public class CarGUI extends JFrame { //CarGUI inherits all the features of JFrame

    private JTextArea leftTextArea; //make 2 JTextAreas for the Jframe
    private JTextArea rightTextArea; 
    private StringBuilder leftSide; //make 2 StringBuilders which we'll later use to append the 2 ArrayLists onto
    private StringBuilder rightSide;

    //Instantiate the two child linked lists we created
    static SortedCarList sortedList = new SortedCarList();
    static UnsortedCarList unSortedList = new UnsortedCarList();

     public CarGUI() //default constructor for the GUI class
{
        // Instance variables
         this( Project 3 );
}


     public CarGUI(String title) //the 1-argument parameter constructor 
        {
            // Call the super class constructor to initialize the super
            // class variables before initializing this class's variables
            super(title); //Inherited the title from the previous constructor

            // Configure the JFrame
            // Configure the JFrame components we inherited
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setSize(500, 500); //setting the size to an arbitrary width and height
            this.setLocation(200, 200);
            this.getContentPane().setLayout(new GridLayout(1, 2)); //1 row and 2 columns, where the 2 lists' toStrings can be appended onto
            this.getContentPane().setBackground(Color.ORANGE);
            this.leftSide = new StringBuilder("Unsorted Cars" + "\n");  //just titling the 2 columns on the JFrame
            this.rightSide = new StringBuilder("Sorted Cars" + "\n");
            this.leftTextArea = new JTextArea(this.leftSide.toString());
            this.rightTextArea = new JTextArea(this.rightSide.toString());
            this.getContentPane().add(this.leftTextArea); //add the currently empty TextAreas to the content panes (the left and right ones)
            this.getContentPane().add(this.rightTextArea);
            //create menu buttons and menu bar
            JMenuItem open = new JMenuItem("Open");
            JMenuItem quit = new JMenuItem("Quit");
            JMenuItem msg = new JMenuItem("Msg");
            JMenuBar menuBar = new JMenuBar();
            JMenu fileMenu = new JMenu("File");
            FileMenuHandler fmh = new FileMenuHandler(this);

            // Add the action listener to the menu items 
            open.addActionListener(fmh);
            quit.addActionListener(fmh);
            msg.addActionListener(fmh);

            // Add the menu items to the file menu
            fileMenu.add(open);
            fileMenu.addSeparator();
            fileMenu.add(quit);
            fileMenu.addSeparator();
            fileMenu.add(msg);
            // Add file menu to the menu bar, and set this gui's
            // menu bar to the menuBar we created above
            menuBar.add(fileMenu);
            this.setJMenuBar(menuBar);
            this.setVisible(true); //without this, the GUI wouldn't even show up
        }


    //Method that will read from a file, sieve through the lines via the StringTokenizer
    //Create Car objects after each line and add them to 2 Linked Lists as CarNodes
    //Move on to the next line and keeps going until there are no more tokens to be found in the file
    //Then it'll append the lists onto StringBuilders which will then be placed into the textAreas
     public void readFile(File file) throws FileNotFoundException{
            Scanner scanner = new Scanner(file.getName()); //scanner will now read through the file, whatever it is
            String line = scanner.nextLine(); //'line' is assigned to the first line of the file
            String delimiter = ",";
            StringTokenizer tokenizer = new StringTokenizer(line, delimiter); //tokenizer will go through the line and separate by ","
            int tokenCount = new StringTokenizer(line, ",").countTokens(); //counts the tokens and makes tokenCount equal to amount of tokens

            while(tokenizer.hasMoreTokens()){ //keeps iterating until there are no more tokens to be found. 
                //if there aren't exactly 4 tokens, print it to the console
                if(tokenCount == 1){ //in the case there's only one text token that can be found
                    String CarMakeUNO = tokenizer.nextToken();
                    System.out.println(CarMakeUNO + "\n"); //print to console
                }
                if(tokenCount == 2){ //in the case there are two tokens that were found in the current line
                    String CarMakeDOS = tokenizer.nextToken();
                    String CarModelDOS = tokenizer.nextToken();
                    System.out.println(CarMakeDOS + ", " + CarModelDOS + "\n"); //print to console
                }
                else if(tokenCount == 3){ //in the case there are three tokens that were found, doing this just in case another .txt file is used
                    String CarMakeTRES = tokenizer.nextToken();
                    String CarModelTRES = tokenizer.nextToken();
                    int CarYearTRES = Integer.parseInt(tokenizer.nextToken());
                    System.out.println(CarMakeTRES + " " + CarModelTRES + " " + CarYearTRES + "\n"); //print to console
                }
                //finally, if there are 4 tokens in the current line, use tokenizer to extract the Make, Model, Year, and Mileage and put them into a new Car Object
                else if (tokenCount == 4){ //since the Make, Model, Year, and Mileage are in fixed order, we can just do it by each subsequent token:
                    String CarMake = tokenizer.nextToken();
                    String CarModel = tokenizer.nextToken();
                    int CarYear = Integer.parseInt(tokenizer.nextToken()); //since years are integers, we need to parse it with parseInt
                    int CarMileage = Integer.parseInt(tokenizer.nextToken());   

                    //make a new object with the above values
                    //newCar(Make, Model, Year, Mileage); 
                    Car newCar = new Car(CarMake, CarModel, CarYear, CarMileage); //put the appropriate variables in the newly instantiated Car object
                    unSortedList.addIt(newCar); //place the Car object into the linked list as a node
                    sortedList.insert(newCar); 

                }//goes through a single line of the file
                if(scanner.hasNextLine()){ //if there are more lines in the file
                    line = scanner.nextLine(); //assigns string line to the next line of the file/goes to the next line
                    tokenizer = new StringTokenizer(line, delimiter); //StringTokenizer tokenizes the current line
                    tokenCount = new StringTokenizer(line, ",").countTokens(); //counts the tokens of the new line
                }
            }//end of while loop (stops when no more tokens)

        scanner.close(); //close the scanner since it's not necessary anymore

        leftSide.append(unSortedList.toString()); //adds the LinkedLists to their respective StringBuilder  
        rightSide.append(sortedList.toString()); //Utilizes the overrided toString in CarList

        //adds the 2 StringBuilders to the 2 JTextAreas
         this.leftTextArea.setText(this.leftSide.toString());
         this.rightTextArea.setText(this.rightSide.toString());

        }
}// end of CarGUI

这是我的 FileMenuHandler类,该类处理actionListener(使JMenuItem表现出我们想要的行为)。它从CarGUI类中调用readFile方法,所选文件(fc.getSelectedFile)是其参数。

public class FileMenuHandler implements ActionListener 
{
//this code is fine
    // Save the reference to the GUI object this FileMenuHandler is 
    // associated with
    private CarGUI gui;

    // Constructor that takes as its parameter the GUI associated 
    // with this FileMenuHandler
    public FileMenuHandler(CarGUI gui) 
    {
        this.gui = gui;
    }

    public void actionPerformed(ActionEvent event) 
    {
        // Get the command name from the event
        String menuName = event.getActionCommand();


        if (menuName.equals("Open")) //if Open is selected
        {
            // Create the object that will choose the file
            JFileChooser fc = new JFileChooser();

            // Attempt to open the file
            int returnVal = fc.showOpenDialog(null);

            // If user selected a file, create File object and pass it to
            // the gui's readFile method
            if (returnVal == JFileChooser.APPROVE_OPTION) 
            {
                File file = fc.getSelectedFile();               
                try {

                    this.gui.readFile(file); //calls readFile method in CarGUI class

                } catch (FileNotFoundException e) {
                    System.out.println(" There is no file");
                    e.printStackTrace();
            }
        } 
        else if (returnVal == JFileChooser.CANCEL_OPTION)
        {
            System.out.println("Open command cancelled by user.");
        }
    } 
    else if (menuName.equals("Quit")) //if Quit is selected
    {
        System.exit(1); //end the program
    }
    else if (menuName.equals("Msg")) //if Msg is selected
    {
        JOptionPane.showMessageDialog(null, "You clicked on \'Msg\'"); //display this message
    } 
} 

}

这是我的主班

public class Project3 {



    public static void main(String arg[]) throws FileNotFoundException{ //main method that enables us to even run this class
                CarGUI testGUI = new CarGUI(); //create a new CarGUI object

        }

    }

我试图尽可能地对其进行注释。它在应该显示链接列表的位置返回2个null。

1 个答案:

答案 0 :(得分:0)

好的。我解决了问题。那不是在读,因为我在我的readFile方法中将.getName放在了文件中...哈哈哈哈。现在一切正常!