简体   繁体   中英

Opening a file with JFileChooser, reading it, and setting values

What I'm trying to do with this GUI is having the person browse for a txt file, and then reading it. When the person clicks the "Read File" button, they should be prompted to choose a file, and then it will read the file and set various values. I am having a few problems with this. First, I'm using scanner to try and set the values, though I am not sure that is the best way. Second, I'm not sure if the file is even being read. I can get the browse for file dialogue to open, but then it freezes, and I have to restart eclipse. How can I use JFileChooser to read a file and set values by reading it?

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;

    public class Display extends JFrame implements ActionListener {
        private static final int FRAME_WIDTH = 400;
        private static final int FRAME_HEIGHT = 350;

        private static final int FRAME_X_ORIGIN = 100;
        private static final int FRAME_Y_ORIGIN = 75;

        private JFrame mainFrame;
        private JCheckBox avgHSCheckBox;
        private JCheckBox avgTSCheckBox;
        private JCheckBox homeworkSDCheckBox;
        private JCheckBox testSDCheckBox;
        private JRadioButton firstClass;
        private JRadioButton secondClass;
        private JRadioButton thirdClass;
        private JRadioButton fourthClass;
        private JButton readFileButton;
        private JButton exitButton;
        private JButton statsButton;
        private JButton clearButton;

        static int numberOfClasses = 3;
        static int numberOfAssignments = 6;
        static int numberOfStudents;
        static int numberOfLabs = 15;
        static int totalHomeworkScore = 0;
        static int totalTestScore = 0;
        static String classYear;
        static String semester;

        public static void main(String[] args) {
            Display frame = new Display();
            frame.setVisible(true);

        }

        public Display() {

            setSize(FRAME_WIDTH, FRAME_HEIGHT);
            setResizable(false);
            setTitle("CSCE155A Course Offering Viewer");
            setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setLayout(new BorderLayout());

            // header
            JPanel header = new JPanel();
            header.setLayout(new GridLayout(2, 1));
            header.setSize(350, 75);
            header.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            header.add(new JLabel("CSCE155A Course Offering Viewer"));
            header.add(new JLabel("First Last"));
            add(header, BorderLayout.NORTH);

            // select stats
            JPanel statsSelect = new JPanel();
            statsSelect.setLayout(new GridLayout(5, 1));
            statsSelect.setSize(100, 100);

            statsSelect.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            statsSelect.add(new JLabel("Please Select: "));
            avgHSCheckBox = new JCheckBox("View Average Homework Score");
            statsSelect.add(avgHSCheckBox);
            avgTSCheckBox = new JCheckBox("View Average Test Score");
            statsSelect.add(avgTSCheckBox);
            homeworkSDCheckBox = new JCheckBox("View SD for Homework Scores");
            statsSelect.add(homeworkSDCheckBox);
            testSDCheckBox = new JCheckBox("View SD for Test Scores");
            statsSelect.add(testSDCheckBox);
            add(statsSelect, BorderLayout.WEST);

            // Course offerings

            JPanel courseOfferings = new JPanel();
            courseOfferings.setLayout(new GridLayout(5, 1));
            courseOfferings.setSize(100, 100);
            courseOfferings.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            courseOfferings.add(new JLabel("Please Select: "));
            firstClass = new JRadioButton(semester + classYear);
            courseOfferings.add(firstClass);
            secondClass = new JRadioButton(semester + classYear);
            courseOfferings.add(secondClass);
            thirdClass = new JRadioButton(semester + classYear);
            courseOfferings.add(thirdClass);
            fourthClass = new JRadioButton(semester + classYear);
            courseOfferings.add(fourthClass);
            add(courseOfferings, BorderLayout.EAST);
            // statistics

            JPanel statistics = new JPanel();
            statistics.setLayout(new GridLayout(5, 1));
            statistics.setSize(200, 150);
            statistics.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            statistics.add(new JLabel("Statistics:"));
            add(statistics, BorderLayout.CENTER);

            // buttons
            JPanel buttons = new JPanel();
            buttons.setLayout(new FlowLayout());
            buttons.setSize(200, 150);
            buttons.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            readFileButton = new JButton("Read File");
            buttons.add(readFileButton);
            exitButton = new JButton("Exit");
            buttons.add(exitButton);
            statsButton = new JButton("Stats");
            buttons.add(statsButton);
            clearButton = new JButton("Clear");
            buttons.add(clearButton);
            add(buttons, BorderLayout.SOUTH);

            avgHSCheckBox.addActionListener(this);
            avgTSCheckBox.addActionListener(this);
            homeworkSDCheckBox.addActionListener(this);
            testSDCheckBox.addActionListener(this);
            firstClass.addActionListener(this);
            secondClass.addActionListener(this);
            thirdClass.addActionListener(this);
            fourthClass.addActionListener(this);
            readFileButton.addActionListener(this);
            exitButton.addActionListener(this);
            statsButton.addActionListener(this);
            clearButton.addActionListener(this);

            setDefaultCloseOperation(EXIT_ON_CLOSE);

        }

        public void actionPerformed(ActionEvent event) {
            Scanner scanner = new Scanner(System.in);
            CourseOffering myCourseOffering = new CourseOffering();
            ComputeStatistics myComputeStatistics = new ComputeStatistics();
            JButton clickedButton = (JButton) event.getSource();
            String buttonText = clickedButton.getText();
            if (buttonText.equals("Read File")) {
                // Create a file chooser
                String filename = File.separator;
                JFileChooser fc = new JFileChooser(new File(filename));
                fc.showOpenDialog(this);
                File selFile = fc.getSelectedFile();

                numberOfClasses = scanner.nextInt();
                for (int i = 0; i < numberOfClasses; i++) {

                    myCourseOffering.setDescription(scanner.next()); // CSCE
                    myCourseOffering.setDescription(scanner.next()); // 155A
                    myCourseOffering.setDescription(scanner.next()); // -
                    myCourseOffering.setDescription(scanner.next()); // Semester
                    semester = myCourseOffering.getDescription();
                    myCourseOffering.setDescription(scanner.next()); // Year
                    classYear = myCourseOffering.getDescription();

                    numberOfStudents = scanner.nextInt(); // Number Of Students
                    myCourseOffering.students = new Student[numberOfStudents];

                    for (int j = 0; j < numberOfStudents; j++) {
                        myCourseOffering.students[j] = new Student();
                        totalTestScore = 0;
                        totalHomeworkScore = 0;
                        // Sets first and last name
                        myCourseOffering.students[j].setFirstName(scanner.next());
                        myCourseOffering.students[j].setLastName(scanner.next());

                        // call assignscores array
                        int[] assignScores = new int[numberOfAssignments];

                        for (int k = 0; k < numberOfAssignments; k++) {
                            assignScores[k] = scanner.nextInt();
                            totalHomeworkScore += assignScores[k];
                        }
                        myCourseOffering.students[j]
                                .setAssignmentScores(assignScores);

                        int[] labScores = new int[numberOfLabs];
                        for (int l = 0; l < numberOfLabs; l++) {
                            labScores[l] = scanner.nextInt();
                            totalHomeworkScore += labScores[l];
                        }
                        myCourseOffering.students[j].setLabScores(labScores);

                        myCourseOffering.students[j].setMidTerm1(scanner.nextInt());
                        totalTestScore += myCourseOffering.students[j]
                                .getMidterm1();

                        myCourseOffering.students[j].setMidterm2(scanner.nextInt());
                        totalTestScore += myCourseOffering.students[j]
                                .getMidterm2();

                        myCourseOffering.students[j]
                                .setFinalExam(scanner.nextInt());
                        totalTestScore += myCourseOffering.students[j]
                                .getFinalExam();

                        myCourseOffering.students[j]
                                .setQuizScore(scanner.nextInt());
                        totalTestScore += myCourseOffering.students[j]
                                .getQuizScore();

                        myCourseOffering.students[j].setAttendanceScore(scanner
                                .nextInt());
                        totalHomeworkScore += myCourseOffering.students[j]
                                .getAttendanceScore();

                        myCourseOffering.students[j].setPatScore(scanner.nextInt());
                        totalTestScore += myCourseOffering.students[j]
                                .getPatScore();

                        myCourseOffering.students[j].setZyanteScore(scanner
                                .nextInt());
                        totalTestScore += myCourseOffering.students[j]
                                .getZyanteScore();

                        myCourseOffering.students[j]
                                .setTotalHomeworkScore(totalHomeworkScore);
                        myCourseOffering.students[j]
                                .setTotalTestScore(totalTestScore);

                    }
                }

            }
        }
    }

The scanner you created uses System.in . You need to create a scanner that operates on the file: Scanner scanner = new Scanner(selFile); .

Also, just FYI, that is an atrocious way to do ActionListeners. I know that tons of examples do that, including the ones from Sun/Oracle, but it's just awful. Attach separate listeners to each button so you're not creating one giant listener that's responsible for everything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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