how do I display txt file data to a jtable? here\'s what I got so far for the te
ID: 3835918 • Letter: H
Question
how do I display txt file data to a jtable? here's what I got so far for the text file data to read, but how do I get it to display on a table?
the departments.txt file only displays departments like in one row, separated by line like
Marketing
Accounting
Sales
public static void main(String[] args) {
// TODO code application logic here
try{
FileReader fr = new FileReader("Departments.txt");
BufferedReader br = new BufferedReader(fr);
String departmentsTextFile;
while ((departmentsTextFile = br.readLine()) != null){
out.println(departmentsTextFile);
}
br.close();
}
catch(IOException e){
out.println("File not found test");
}
java.io.File departmentsFile = new java.io.File("Departments.txt");
try {
Scanner input = new Scanner(departmentsFile);
while(input.hasNext()){
String num = input.nextLine();//grabs line
****HERE IS WHERE I WOULD ADD IT TO THE JTABLE CALLED ASSIGNMENTSTABLE -ONE COLUMN TOTAL
}
}
catch (FileNotFoundException e){
System.err.format("File does not exist");
Explanation / Answer
package javajtable;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public class JavaJTable {
JFrame f;
ArrayList al;
JavaJTable() {
f=new JFrame();
try{
FileReader fr = new FileReader("C:\Users\Binay_Pandey01\Desktop\Departments.txt");
BufferedReader br = new BufferedReader(fr);
String departmentsTextFile;
al= new ArrayList();
while ((departmentsTextFile = br.readLine()) != null){
System.out.println(departmentsTextFile);
al.add(departmentsTextFile);
}
br.close();
} catch (Exception ex) {
Logger.getLogger(JavaJTable.class.getName()).log(Level.SEVERE, null, ex);
}finally{
}
String data[][]=new String[al.size()][1];
for(int i=0;i<al.size();i++){
data[i][0]= (String)al.get(i);
}
String column[]={"Field"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,100,300);
JScrollPane jsp=new JScrollPane(jt);
f.add(jsp);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args) {
new JavaJTable();
}
}
sample data for Departments.txt (Departments.txt is input file and below data is present in file)
Sales
Marketing
TestField
Output :
Sales
Marketing
TestField
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.