从文件中读取并在textarea中显示java

时间:2012-12-08 13:37:56

标签: java swing user-interface file-io jtextarea

我有以下代码从测试文件中读取名称,工作正常

public class Names {

    Scanner scan;
    static String Firstname;
    static String Surname;
    static String Fullname;

    public void OpenFile()
    {
        try
        {
            scan = new Scanner(new File("test.txt"));
            System.out.println("File found!");
        }

        catch(Exception e)
        {
            System.out.println("File not found");
        }
    }

    public void ReadFile()
    {
        while(scan.hasNext())
        {
            Firstname = scan.next();
            Surname = scan.next();
            Fullname =  Firstname + " " + Surname;

            System.out.println(Fullname);
        }
    }

    public void CloseFile()
    {
        scan.close();
    }
}

然后我有这个调用Names类的主类。它工作得很好,除了它只显示测试文件中的姓氏。

public class NameSwing implements ActionListener {

    private JTextArea tf = new JTextArea(20,20);
    private JFrame f = new JFrame("names");
    private JButton b = new JButton("view");

    static String fullName;

    public NameSwing(){
        f.add(new JLabel("Name"));
        tf.setEditable(true);
        f.add(tf);

        b.addActionListener(this);
        f.add(b);

        f.setLayout(new FlowLayout());
        f.setSize(300,100);
        f.setVisible(true);

    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource()==b)
        {
            tf.setText(fullName);
        }
    }       

    public static void main(String[] args) throws FileNotFoundException, IOException {
        NameSwing nameSwing = new NameSwing();

        Names t = new Names();
        t.OpenFile();
        t.ReadFile();
        t.CloseFile();

        fullName = Names.Fullname;   
    }

}

这是测试文件内容。

Nick Harris

Olly Dean

艾玛萨蒙斯

Henry Blackwell

如何让textarea显示读者的所有名字,而不只是姓氏?

4 个答案:

答案 0 :(得分:4)

抛弃你的Names类,因为它不是很有帮助,并且过度使用静态字段对它有害。我认为最好的解决方案是:

  • 创建一个包含文本文件的文件
  • 使用此文件
  • 创建FileReader对象
  • 使用此选项创建BufferedReader对象
  • 调用传入BufferedReader
  • 的JTextArea的read(...)方法
  • 你做完了。

即,在actionPerformed:

BufferedRead buffReader = null;
try {
  File file = new File("test.txt");
  FileReader fileReader = new FileReader(file);
  buffReader = new BufferedReader(fileReader);
  tf.read(buffReader, "file.txt");
}  catch (WhateverExceptionsNeedToBeCaught e) {
  e.printStackTrace();
} finally {
  // close your BufferedReader
}

答案 1 :(得分:2)

  • 您没有充分理由使用太多静态字段。一直用 静态字段,如果您打算使您的类成为工厂类,那么 在这种情况下是不合适的。
  • 您正在打破封装的基本规则,为每个方法提供public Access Specifier,而不需要它。
  • 您可以简单地使用setSize(),而不是调用pack(),这可以比您指定的任意值更好地确定Container的尺寸。
  • 请阅读Concurrency in Swing,因为在我看来,你的知识在这方面有点短暂。
  • 请务必了解Java Naming Conventions
  • 此外,你可以简单地使用StringBuilder类,为你做这件事。看看你的修改后的代码。请问任何超出您掌握的事情,我很乐意为此提供帮助。

修改后的代码:

import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class NameSwing implements ActionListener {

    private Names t;
    private JTextArea tf = new JTextArea(20,20);
    private JFrame f = new JFrame("names");
    private JButton b = new JButton("view");

    public NameSwing(){

        performFileRelatedTask();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel contentPane = new JPanel();
        contentPane.setLayout(new BorderLayout(5, 5));

        JScrollPane scroller = new JScrollPane();
        scroller.setBorder(BorderFactory.createLineBorder(Color.BLUE.darker(), 5));

        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new BorderLayout(5, 5));
        centerPanel.add(new JLabel("Name", JLabel.CENTER), BorderLayout.PAGE_START);        
        tf.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        tf.setEditable(true);
        centerPanel.add(tf, BorderLayout.CENTER);
        scroller.setViewportView(centerPanel);

        JPanel footerPanel = new JPanel();
        b.addActionListener(this);
        footerPanel.add(b);

        contentPane.add(scroller, BorderLayout.CENTER);
        contentPane.add(footerPanel, BorderLayout.PAGE_END);

        f.setContentPane(contentPane);
        f.pack();
        f.setLocationByPlatform(true);
        f.setVisible(true);
    }

    private void performFileRelatedTask()
    {
        t = new Names();
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource()==b)
        {
            tf.setText(t.getFullNames().toString());
        }
    }       

    public static void main(String[] args) throws FileNotFoundException, IOException {

        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new NameSwing();
            }
        });                
    }

}

class Names {

    private Scanner scan;
    private String firstname;
    private String surname;
    private StringBuilder fullnames;

    public Names()
    {
        fullnames = new StringBuilder();
        openFile();
        readFile();
        closeFile();
    }

    public StringBuilder getFullNames()
    {
        return fullnames;
    }

    private void openFile()
    {
        try
        {
            scan = new Scanner(new File("test.txt"));
            System.out.println("File found!");
        }

        catch(Exception e)
        {
            System.out.println("File not found");
        }
    }

    private void readFile()
    {
        while(scan.hasNext())
        {
            firstname = scan.next();
            surname = scan.next();
            fullnames.append(firstname + " " + surname + "\n");
        }
    }

    private void closeFile()
    {
        scan.close();
    }
}

答案 2 :(得分:1)

您需要更改

 while(scan.hasNext())
        {
            Firstname = scan.next();
            Surname = scan.next();
            //Assigning each time instead of append
            Fullname =  Firstname + " " + Surname;
        }

以下是完整修复:

public class NameSwing implements ActionListener {

    private JTextArea textArea = new JTextArea(20, 20);
    private JFrame frame = new JFrame("Names");
    private JButton btnView = new JButton("View");
    private Scanner scanner;
    private String firstName;
    private String surName;
    private String fullName;

    public NameSwing() {
        frame.add(new JLabel("Name"));
        textArea.setEditable(true);
        frame.add(textArea);

        btnView.addActionListener(this);
        frame.add(btnView);

        frame.setLayout(new FlowLayout());
        frame.setSize(300, 100);
        frame.setVisible(true);

    }

    public void OpenFile() {
        try {
            scanner = new Scanner(new File("test.txt"));
            System.out.println("File found!");
        } catch (Exception e) {
            System.out.println("File not found");
        }
    }

    public void ReadFile() {
        while (scanner.hasNext()) {
            firstName = scanner.next();
            surName = scanner.next();
            // assign first time
            if( fullName == null ) {
                fullName = firstName + " " + surName;
            } else {
                fullName = fullName + "\n" + firstName + " " + surName;
            }

            System.out.println(fullName);
        }
    }

    public void CloseFile() {
        scanner.close();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == btnView) {
            textArea.setText(fullName);
        }
    }

    public static void main(String[] args) throws FileNotFoundException, IOException {
        NameSwing nameSwing = new NameSwing();
        nameSwing.OpenFile();
        nameSwing.ReadFile();
        nameSwing.CloseFile();
    }
}

答案 3 :(得分:1)

问题在于

Fullname = Firstname + " " + Surname;

成功

Fullname += Firstname + " " + Surname; + "\n"

你的问题解决了:)