【问题标题】:reading from file and showing in textarea java从文件读取并在 textarea java 中显示
【发布时间】:2012-12-08 13:37:55
【问题描述】:

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

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 显示来自读者的所有姓名,而不仅仅是姓氏?

【问题讨论】:

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


    【解决方案1】:

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

    • 创建一个包含您的文本文件的文件
    • 用这个文件创建一个 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
    }
    

    【讨论】:

      【解决方案2】:
      • 您无缘无故地使用了太多静态字段。始终使用 静态字段,如果你打算让你的类成为工厂类,它 在这种情况下是不合适的。
      • 您打破了封装的基本规则,为每个方法提供public Access Specifier,而不需要它。
      • 您可以简单地使用pack(),而不是调用setSize(),它可以比您指定的任意值更好地确定容器的尺寸。
      • 请务必阅读有关 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();
          }
      }
      

      【讨论】:

      • +1 提供好的建议;还可以考虑new JScrollPane(centerPanel) 并将边框添加到周围的组件,例如滚动窗格。
      【解决方案3】:

      问题出在一行

      Fullname = Firstname + " " + Surname;.

      做起来

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

      你的问题解决了:)

      【讨论】:

        【解决方案4】:

        你需要改变

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-09
          • 1970-01-01
          • 2011-09-29
          相关资源
          最近更新 更多