简体   繁体   中英

How do I add data from a file to a JTable?

Here is my method so far:

public void readfile(JTable table) {
        try{
        BufferedReader in = new BufferedReader( new FileReader("out.txt"));     
        for(int i = 0; i<10; i++) {
            for(int j = 0; j<5; j++) {
                table.setValueAt(in.readLine(), i, j);
            }
        }
        in.close();
        }catch (Exception e) {
        System.err.println("error: " + e.getMessage());
        }   
    }

Here are the contents of out.txt:

test1
test2
test3
test4
test5

Where I run the program and attempt to load the file to the table, nothing happens. I also get an output that says the following:

error: 0 >= 0

Help me please?

I would narrow your problem down to a smaller problem, solve this smaller problem, and then widen it until you have want you want.

  1. Think of the contents of a File as a big blob of text.
  2. Think of the table as a Vector of Vectors.

Smaller problem: How do I convert a big blob of text into a Vector of Vectors? You need to be able to sove this problem first before tackling File I/O or DefaultTableModels.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM