如何创建一个读取文件并将信息存储到数组中的void方法,然后将该方法中的文本显示到JTextArea中?

时间:2013-12-10 02:02:13

标签: java swing jtextfield jtextarea

所以我创建了一个读取文件的方法,并且对于该文本文件中的每一行,该方法将它们输入到数组中。现在我想弄清楚如何将整个方法(readFile方法)显示到我的JTextArea中。请帮帮忙?

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


public class NameViewer {

JTextField nameTF;
JTextArea displayArea;
NameRecord[] nameList ;

public static void main( String[] arg ) {
    NameViewer app = new NameViewer() ;

}

public NameViewer() {

    JFrame frame = new JFrame( "Name Surfer" ) ;
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ) ;

    JPanel mainPanel = new JPanel() ;
    mainPanel.setLayout( new BorderLayout() ) ;

    displayArea = new JTextArea(25, 50) ;
    displayArea.setEditable(false);
    JScrollPane scrollPane = new JScrollPane( displayArea ) ;
    mainPanel.add( BorderLayout.CENTER, scrollPane ) ;

    displayArea.setText(readFile());

    JPanel controlPanel = new JPanel() ;
    controlPanel.setLayout( new GridLayout(1, 3) ) ;

    nameTF = new JTextField( 7 ) ;
    controlPanel.add( nameTF ) ;

    JButton find = new JButton(" Find " );
    controlPanel.add(find) ;
    find.addActionListener( new Listener());

    JButton match = new JButton(" Match " );
    controlPanel.add(match) ;
    match.addActionListener( new Listener());

    mainPanel.add( BorderLayout.SOUTH, controlPanel ) ;

    frame.add( mainPanel ) ;
    frame.setVisible( true ) ;
    frame.setResizable(false);
    frame.pack() ;
}

public class Listener implements ActionListener {
    public void actionPerformed( ActionEvent e ) {


    }
}

public String readFile() {
    StringBuilder sb = new StringBuilder();
    try {
        String inputLine;
        Scanner inFile = new Scanner (new File ("baby-names.txt"));

        int i = 0;
        int num = inFile.nextInt();
        nameList = new NameRecord[num];

        while ( inFile.hasNext() ) {
            inputLine = inFile.nextLine();
            System.out.println(nameList);        

            nameList[i] = new NameRecord(inputLine);
            displayArea.append(nameList[i] +"\n");
            i++ ;
        }
    } catch(IOException io) {
        System.out.println(io) ;
    }
     return sb.toString();

}  // readFile()


}

继承人我的姓名记录:

import java.util.Scanner;

/**
A class to represent the data for one name over the 
decades.
KEEP THIS IN A SEPARATE FILE!
*/
public class NameRecord {

private String name ;
private int[] rank ;
public static final int START = 1900 ;
public static final int DECADES = 11 ;

/**
 * 
 * @param record
 */
public NameRecord(String record){
    //use a Scanner to get the data from the record
    Scanner line = new Scanner (record);
    name = line.next();

    rank = new int[DECADES] ;
    for(int i=0; i<DECADES; i++)
        rank[i] = line.nextInt();
}

public String getName() {
    return name ;
}

public void setName(String newName) {
    name = newName;
}

public int getRank(int d) {
    int decadeRank = rank[d];
    return decadeRank;
}
/** returns the best decade
*
* @return the best decade
*/  
public int bestDecade() {
    int best = rank[0];
    for(int i=1; i<DECADES; i++)
        if(rank[i] > best)
            best = rank[i];
    return best;
}
/** toString method for NameRecord
*
* @return student's name and rank
*/  
public String toString() {
    String result = getName() ;

    for(int i=0; i<DECADES; i++)
        result = result + " " + rank[i] ;

    return result ;
}

}

2 个答案:

答案 0 :(得分:0)

由于我没有看到您使用数组设置文本的位置,我只是推荐这个

while ( inFile.hasNext() ) {
        inputLine = inFile.nextLine();
        System.out.println(inputLine);       

        nameList[i] = new NameRecord(inputLine);
        displayArea.append(nameList[i] + "\n");
        i++ ;
}

我刚刚添加了一个append语句,它将附加到文本区域。

另请注意,您应该覆盖toString()中的NameRecord方法,以便获得所需的字符串输出

您不需要将fileName的参数传递给方法,因为您已经在方法中使用了文字。

另一个建议是,让方法返回一个String

 String readFile() {
        StringBuilder sb = new StringBuilder();
        try {
            String inputLine;
            Scanner inFile = new Scanner (new File ("baby-names.txt"));

            int i = 0;
            int num = inFile.nextInt();
            nameList = new NameRecord[num];

            while ( inFile.hasNext() ) {
                inputLine = inFile.nextLine();
                System.out.println(inputLine);       

                nameList[i] = new NameRecord(inputLine);
                sb.append(nameList[i]);
                i++ ;
        }
    } catch(IOException io) {
        System.out.println(io) ;
    }

    return sb.toString()'
}

然后在你的构造函数

displayArea.setText(readFile());

编辑:想要的结果试试这个

String readFile() {
        StringBuilder sb = new StringBuilder();
        sb.append("FIND RESULTS FOR Trinity\n\n");
        sb.append("Decade\tRank\n");
        sb.append("------\t-----\n");
        try {
            String inputLine;
            Scanner inFile = new Scanner (new File ("baby-names.txt"));

            int i = 0;
            int num = inFile.nextInt();
            nameList = new NameRecord[num];

            while ( inFile.hasNext() ) {
                inputLine = inFile.nextLine();
                System.out.println(inputLine);       

                nameList[i] = new NameRecord(inputLine);
                sb.append(nameList[i].getDecade() + "\t" + nameList[i].getRank() + "\n");
                i++ ;
        }
    } catch(IOException io) {
        System.out.println(io) ;
    }

    return sb.toString();
}

假设您的getDecade()班级中有getRank()NameRecord

编辑:完成可运行程序

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

public class NameViewer {

    JTextField nameTF;
    JTextArea displayArea;
    NameRecord[] namesArray;


    public static void main(String[] arg) {
        NameViewer app = new NameViewer();

    }

    public NameViewer() {

        JFrame frame = new JFrame("Name Surfer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());

        displayArea = new JTextArea(25, 50);
        displayArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(displayArea);
        mainPanel.add(BorderLayout.CENTER, scrollPane);

        JPanel controlPanel = new JPanel();
        controlPanel.setLayout(new GridLayout(1, 3));

        nameTF = new JTextField(7);
        controlPanel.add(nameTF);

        JButton find = new JButton(" Find ");
        controlPanel.add(find);
        find.addActionListener(new Listener());

        JButton match = new JButton(" Match ");
        controlPanel.add(match);
        match.addActionListener(new Listener());

        mainPanel.add(BorderLayout.SOUTH, controlPanel);

        read("names.txt");

        frame.add(mainPanel);
        frame.setVisible(true);
        frame.setResizable(false);
        frame.pack();
    }

    public class Listener implements ActionListener {

        public void actionPerformed(ActionEvent e) {

        }
    }

    private void read(String filename) {
        StringBuilder sb = new StringBuilder();
        try {
            String inputLine;
            Scanner inFile = new Scanner(new File(filename));

            int i = 0;
            int num = Integer.parseInt(inFile.nextLine().trim());
            namesArray = new NameRecord[num];

            String inputString;
            while (inFile.hasNextLine()) {
                inputString = inFile.nextLine();
                namesArray[i] = new NameRecord(inputString);
                displayArea.append(namesArray[i].toString() + "\n");
            }
        } catch (IOException io) {
            System.out.println(io);
        }
    }  // readFile()
}

public class NameRecord {

    private String name;
    private final static int NUM_OF_DECADES = 11;
    private int[] ranks;

    public NameRecord(String inputString) {
        String[] split = inputString.split("\\s+");

        this.name = split[0];

        ranks = new int[NUM_OF_DECADES];

        for (int i = 1; i < NUM_OF_DECADES; i++) {
            ranks[i - 1] = Integer.parseInt(split[i]);
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String newName) {
        name = newName;
    }

    public int getHighRank(int d) {
        int decadeRank = ranks[d];
        return decadeRank;
    }

    public int[] getRank(){
        return ranks;
    }

    public int bestDecade() {
        int best = ranks[0];
        for (int i = 0; i < NUM_OF_DECADES; i++) {
            if (ranks[i] > best) {
                best = ranks[i];
            }
        }
        return best;
    }



    @Override
    public String toString() {
        String result = getName();

        for (int i = 0; i < NUM_OF_DECADES; i++) {
            result = result + " " + ranks[i];
        }

        return result;
    }

}

答案 1 :(得分:0)

我建议您从readFile方法输出一个String数组,并从main中调用它。

String [] storage = readFile(fileName);


for(int i=0; i<storage.length; i++){
    displayArea.append(storage[i] + "\n");
}

如果您希望每个元素位于不同的行上,则添加\ n是可选的。

或者,如果您只想在readFile方法中执行此操作,

 while ( inFile.hasNext() ) {
        inputLine = inFile.nextLine();
        System.out.println(inputLine);       

        nameList[i] = new NameRecord(inputLine);
        displayArea.append(nameList[i] +"\n");
        i++ ;
    }