简体   繁体   English

存储从txt文件到字符串java的行

[英]storing line from txt file to string java

My program reads a txt file and shows each line in a Jlabel when the Jbutton is clicked. 我的程序读取txt文件,并在单击Jbutton时在Jlabel中显示每一行。

When the program runs and the Jbutton is clicked nothing appears in the JLabel. 当程序运行并单击Jbutton时,JLabel中没有任何内容。

I believe this is because I am not calling the String line correctly in the readFile method. 我相信这是因为我没有在readFile方法中正确调用String行。

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

import javax.swing.*;

public class Driver {

        List<String> lines;

        static String line = "";

        static Scanner scanner = new Scanner(System.in);

        String s = "Welcome Students!";
        String b = "Start!";
        private JFrame f;
        private JPanel p;

        JFrame frame = new JFrame();

        JButton b1 = new JButton(b);

        JLabel jl = new JLabel(s);

        int i;

        private int clicked;

        public Driver() {
                gui();
        }

        public void gui() {
                lines = readLinesFromFile();
                i = 0;
                f = new JFrame("Flash Card Program");
                p = new JPanel();
                f.setLayout(new GridLayout(2, 1));
                f.add(jl);
                f.add(p);
                p.setLayout(new GridLayout(2, 1));
                p.add(b1);

                jl.setHorizontalAlignment(JLabel.CENTER);

                // pack the frame for better cross platform support
                f.pack();
                // Make it visible
                f.setVisible(true);
                f.setSize(500, 400); // default size is 0,0
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                b1.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        jl.setText(lines.get(i));
                        i++;
                        if ( i > lines.size() ) {
                            i = 0;
                        }
                        if (b1.getText().equals("Click For Answer")) {
                            b1.setText("Next Question");
                        } else {
                            b1.setText("Click For Answer");
                        }
                    }
                });


            b1.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {

                            if (clicked++ == 10) {

                                    Object[] options = { "No, thanks", "Yes, please" };

                                    int response = JOptionPane.showOptionDialog(frame,
                                                    "Would you like more math questions? ",
                                                    "Math Questions", JOptionPane.YES_NO_CANCEL_OPTION,
                                                    JOptionPane.QUESTION_MESSAGE, null, options,
                                                    options[1]);

                                    if (response == 1)
                                            clicked = 1; // reset
                                    else
                                            System.exit(0);
                            }
                    }
            }); 
    }


        public static List<String> readLinesFromFile() {
             List<String> lines = new ArrayList<String>();
            try {
                scanner = new Scanner(new File("upload.txt"));
                if (scanner.hasNext()){
                    lines.add(scanner.nextLine());
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            return lines;
        }

        private static void readFile(File file) throws FileNotFoundException{
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
            line = scanner.nextLine();
            }
            scanner.close();
        }


        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        new Driver();
                        readFile(new File("upload.txt"));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
}

If you want to set the label for the jl field with one of the lines from the text file, then you need to do the following: 如果要使用文本文件中的任一行设置jl字段的标签,则需要执行以下操作:

  1. add a List field inside your Driver class: 在Driver类中添加一个List字段:

     public class Driver { List<String> lines; //other fields that you need } 
  2. in the gui() method, on the first line, initialize the lines field with the actual lines from the file, and initialize i counter with 0: gui()方法的第一行中,使用文件中的实际行来初始化lines字段,并使用0初始化i计数器:

     public void gui() { lines = readLinesFromFile(); i = 0; //other code 
  3. add the following method: 添加以下方法:

     public static List<String> readLinesFromFile() { List<String> lines = new ArrayList<String>(); try { Scanner scanner = new Scanner(new File("upload.txt")); if (scanner.hasNext()){ lines.add(scanner.nextLine()); } } catch (FileNotFoundException e) { e.printStackTrace(); } return lines; } 
  4. change the first ActionListener for b1 with the following: 使用以下命令将b1的第一个ActionListener更改为:

      b1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jl.setText(lines.get(i)); i++; if ( i > lines.size() ) { i = 0; } if (b1.getText().equals("Click For Answer")) { b1.setText("Next Question"); } else { b1.setText("Click For Answer"); } } }); 

Also, using this implementation, you don't need the line variable anymore, because you set the text for the label to one of the values from the lines field. 同样,使用此实现,您不再需要line变量,因为您将标签的文本设置为lines字段中的值之一。

NOTE: if i gets higher that the actual number of lines in the file, it is reset to 0. If you don't want this, just change the if block in the ActionListener that checks the size 注意:如果高于文件中的实际行数,则将其重置为0。如果您不希望这样做,只需更改ActionListener中的if块即可检查大小

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

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