我正在试图实现JFileChooser以便能够从另一个程序创建的两个.txt文件中进行选择。我创建了一个相当简单的JTable,它将根据我给它的路径从一个.txt文件中加载数据。但是,我对如何使JTable实现JFileChooser能够选择其中一个文件并使数据显示在正确的单元格中一无所知。下面是JTable的代码和其中一个文件的一小部分数据示例
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class Maingui {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
new Maingui().createUI();
}
};
EventQueue.invokeLater(r);
}
private void createUI() {
try {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JTable table = new JTable();
String readLine = null;
StudentTableModel tableModel = new StudentTableModel();
File file = new File("/Users/Will/Desktop/BenchmarkSort.txt");
FileReader reader = new FileReader(file);
BufferedReader bufReader = new BufferedReader(reader);
List<Line> studentList = new ArrayList<Line>();
while((readLine = bufReader.readLine()) != null) {
String[] splitData = readLine.split(";");
Line line = new Line();
line.setName(splitData[0]);
studentList.add(line);
}
tableModel.setList(studentList);
table.setModel(tableModel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.setTitle("Benchmark Sorter");
frame.pack();
frame.setVisible(true);
} catch(IOException ex) {}
}
class Line {
private String name;
private String number;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class StudentTableModel extends AbstractTableModel {
private List<Line> list = new ArrayList<Line>();
private String[] columnNames = { "Size", "Avg Count", "Coef Count", "Avg Time", "Coef Time"};
public void setList(List<Line> list) {
this.list = list;
fireTableDataChanged();
}
@Override
public String getColumnName(int column) {
return columnNames[column];
}
public int getRowCount() {
return list.size();
}
public int getColumnCount() {
return columnNames.length;
}
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case 0:
return list.get(rowIndex).getName();
default:
return null;
}
}
}
}
。txt中的数据
Data Set Size (n): 100
Iterative Selection Sort Results:
Average Critical Operation Count: 1090
Standard Deviation of Count: 770
Average Execution Time: 10340
JFileChooser确实与问题无关。
您需要开始学习如何使用文件中的数据创建List<Line>
ArrayList,以便您可以调用setList()
方法。
因此,一旦有了要读取的文件名,就需要创建一个BufferedFileReader来读取文件。
然后对文件中的每一行数据:
Line
对象的实例Line
对象添加到您的ArrayList读取完文件后,在setList(…)
上调用StudentTableModel
方法。
因此,首先使上述逻辑与硬编码的文件名一起工作。然后,一旦工作,您就可以使用JFileChooser动态获取文件名。