user1386999
user1386999

Reputation: 75

reading from file and showing in textarea java

I have the following code which reads names from the test file, which works fine

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

Then I have this main class which calls the Names class. it works fine apart from it only shows the last names from the test file.

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

}

This is the test file content.

Nick Harris

Olly Dean

Emma Sammons

Henry Blackwell

How can I get the textarea to show all of the names from the reader, and not just the last name?

Upvotes: 2

Views: 9199

Answers (4)

nIcE cOw
nIcE cOw

Reputation: 24626

  • You are using too many static fields for no good reasons. Always use static fields if you intend to make your class a Factory Class, which in this case is not appropriate.
  • You are breaking the fundamental rule of encapsulation, by providing each method with a public Access Specifier, without the need of it.
  • Instead of calling setSize(), you can simply use pack(), which can determine the dimensions of the Container, in a much better way, than the arbitrary values you had specified.
  • Please do read about Concurrency in Swing, since appears to me your knowledge is a bit short on that front.
  • Please do learn Java Naming Conventions.
  • Moreover, you can simply use a StringBuilder Class, to do this thingy for you. Have a look at the modified code of yours. Do ask anything that is beyond your grasp, I be happy to help on that.

MODIFIED CODE :

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

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285430

Throw out your Names class as it isn't very helpful and over-uses static fields to its detriment. The best solution in my mind is to:

  • Create a File that holds your text file
  • Create a FileReader object with this File
  • Use this to create a BufferedReader object
  • call the JTextArea's read(...) method passing in the BufferedReader
  • And your done.

i.e., in 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
}

Upvotes: 4

vels4j
vels4j

Reputation: 11298

Here you need the change

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

Here is complete fix:

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

Upvotes: 1

Fahim Parkar
Fahim Parkar

Reputation: 31647

The problem is at line

Fullname = Firstname + " " + Surname;.

Make it

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

You problem is solved :)

Upvotes: 1

Related Questions