0

java swing 和动作监听器的新手。我想要的是逐行显示文本文件,当我点击 JButton 时更改行。对于我正在使用的分隔符,或 | 我到目前为止的代码是:

next.addActionListener(new ActionListener (){
        public void actionPerformed(ActionEvent e){
            if (next.equals(next)) {
              {
                try{
                    File data = new File("player.txt");
                    Scanner scanner = new Scanner(data);

                    if (scanner != null){
                        scanner.useDelimiter(",|*");
                        if (scanner.hasNextLine()){
                            {

                                    textArea.append(scanner.nextLine() + "\n");
                            }
                        }
                            scanner.close();
                    }
              }
                catch (FileNotFoundException ex){}
              }
         }

        }//End ActionPerformed
    });//End ActionListener

每次我点击按钮时,这段代码只是读取文本文件的第一行。

4

1 回答 1

0

如果你想用作分隔符,,或者|你应该把它写成

useDelimiter(",|\\|");

或者

useDelimiter("[,\\|]");

此外,如果您想使用此分隔符,您应该使用scanner.next()而不是scanner.nextLine().

Lastly to read entire content of file you should use while (scanner.hasNext()) rather then if (scanner.hasNextLine()), or create scanner outside of ActionListener so your action could read next line with each button-click (now your ActionListener creates new Scanner with each button click so it starts reading file from beginning).

于 2013-03-29T23:08:58.767 回答