2

我有以下代码从测试文件中读取名称,效果很好

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;   
    }

}

这是测试文件的内容。

尼克哈里斯

奥利迪恩

艾玛萨蒙斯

亨利布莱克威尔

如何让 textarea 显示来自读者的所有姓名,而不仅仅是姓氏?

4

4 回答 4

4

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

  • 创建一个包含您的文本文件的文件
  • 用这个 File 创建一个 FileReader 对象
  • 使用它来创建一个 BufferedReader 对象
  • 调用 JTextArea 的read(...)方法传入 BufferedReader
  • 你完成了。

即,在 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
}
于 2012-12-08T13:47:29.953 回答
2
  • 您无缘无故地使用了太多静态字段。如果您打算使您的类成为工厂类,请始终使用静态字段,这在这种情况下是不合适的。
  • 你打破了封装的基本规则,通过为每个方法提供一个public Access Specifier,而不需要它。
  • 除了调用setSize(),您可以简单地使用pack(),它可以以比您指定的任意值更好的方式确定 Container 的尺寸。
  • 请阅读有关Swing 中的并发,因为在我看来,您在这方面的知识有点短。
  • 请务必学习Java 命名约定
  • 此外,您可以简单地使用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();
    }
}
于 2012-12-08T16:07:52.157 回答
1

问题出在一线

Fullname = Firstname + " " + Surname;.

做了

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

你的问题解决了:)

于 2012-12-08T13:56:33.343 回答
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();
    }
}
于 2012-12-08T13:51:05.260 回答