从CSV文件读取数据并将其显示在JTable中 [英] Reading data from CSV file and displaying it in a JTable
问题描述
我试图从CSV文件读取数据并将其显示在JTable上,但是我遇到了一些问题。我是一个noob,所以请忍受我。我已经看了几个来源的示例代码,但无济于事。表格显示,但是是空白的。我知道我正在阅读数据,因为我可以打印它。我怀疑我的ModelTable设置有问题。任何帮助将不胜感激。
package t1data;
import java.util。*;
import java.awt.event。*;
import javax.swing。*;
import java.awt.BorderLayout;
import java.awt。*;
import javax.swing.border.EmptyBorder;
import java.io. *;
import javax.swing.table。*;
public class T1Data extends JPanel implements ActionListener {
public T1Data(){
super(new BorderLayout(3,3));
JTable Table = new JTable(new MyModel());
Table.setPreferredScrollableViewportSize(new Dimension(700,70));
Table.setFillsViewportHeight(true);
JPanel ButtonOpen = new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton OpenFile = new JButton(Open);
JButton SaveFile = new JButton(Save);
ButtonOpen.add(OpenFile);
add(ButtonOpen,BorderLayout.SOUTH);
OpenFile.addActionListener(this);
SaveFile.addActionListener(this);
//创建滚动窗格并添加表格。
JScrollPane scrollPane = new JScrollPane(Table);
//将滚动窗格添加到此面板。
add(scrollPane,BorderLayout.CENTER);
//添加一个漂亮的边框
setBorder(new EmptyBorder(5,5,5,5));
$ b public void actionPerformed(ActionEvent Event){
JFileChooser fc = new JFileChooser();
boolean pressed = true;
$ b $ // if(Event.getSource()== OpenFile){
if(pressed){
int ReturnVal = fc.showOpenDialog(null);
// if(ReturnVal == JFileChooser.APPROVE_OPTION){
CSVFile Rd = new CSVFile();
// ArrayList< String []> Rs2 = new ArrayList<>();
MyModel NewModel = new MyModel();
文件DataFile = fc.getSelectedFile();
ArrayList< String []> Rs2 = Rd.ReadCSVfile(DataFile);
NewModel.AddCSVData(Rs2);
System.out.println(Rows:+ NewModel.getRowCount());
System.out.println(Cols:+ NewModel.getColumnCount());
//读取CSV文件的方法
public class CSVFile {
private ArrayList< String []> Rs = new ArrayList<>();
private String [] OneRow;
public ArrayList< String []> ReadCSVfile(File DataFile){
try {
BufferedReader brd = new BufferedReader(new FileReader(DataFile));
while(brd.readLine()!= null){
String st = brd.readLine();
OneRow = st.split(,| \\\s |;);
Rsadd(OneRow);
System.out.println(Arrays.toString(OneRow));
} // while while
} // end of try
catch(Exception e){
String errmsg = e.getMessage();
System.out.println(File not found:+ errmsg);
} //结束捕获
返回Rs;
} // ReadFile方法结束
} // CSVFile类结束
private static void createAndShowGUI(){
//创建并设置窗口。
JFrame frame = new JFrame(T1Data);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//创建并设置内容窗格。
T1Data newContentPane = new T1Data();
frame.setContentPane(newContentPane);
//显示窗口。
frame.pack();
frame.setVisible(true);
$ b $ class MyModel extends AbstractTableModel {
private String [] columnNames = {1,2,3,4,5, 6\" };
private ArrayList< String []> Data = new ArrayList<>();
public void AddCSVData(ArrayList< String []> DataIn){
this.Data = DataIn;
this.fireTableDataChanged();
}
@Override
public int getColumnCount(){
return columnNames.length; // length;
@Override
public int getRowCount(){
return Data.size();
}
@Override
public String getColumnName(int col){
return columnNames [col];
@Override
public Object getValueAt(int row,int col)
{
return Data.get(row)[col];
$ b public static void main(String [] args){
//为事件派发线程安排作业:
//创建并显示此应用程序的GUI。
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
createAndShowGUI();
}
});
// T1Data.createAndShowGUI();
$ / code $ / pre
解决方案我已经使用了命名传递,但是你应该阅读我上面有关变量和类的Java命名约定的评论。)
你创建一个表传递一个新的
稍后,您将创建一个(单独的)新的 MyModel
在> actionPerformed()
:
$ b
MyModel NewModel = new MyModel ;
File DataFile = fc.getSelectedFile();
ArrayList< String []> Rs2 = Rd.ReadCSVfile(DataFile);
NewModel.AddCSVData(Rs2);
问题是你永远不要调用 table.setModel(NewModel)
。
为了解决这个问题,将表格变量存储为字段 T1Data
类,以便稍后可以引用它:
private final JTable表;
$ b public T1Data(){
super(new BorderLayout(3,3));
this.table = new JTable(new MyModel());
this.table.setPreferredScrollableViewportSize(new Dimension(700,70));
this.table.setFillsViewportHeight(true);
然后在 actionPerformed()
:
this.table.setModel(NewModel);
I am trying to read data from a CSV file and display it on a JTable but i have a few problems. I am a noob so please bear with me. I have looked at and incorporated example code from several sources but to no avail. The table shows but it is blank. I know i am reading the data because i can print it. I suspect there is something wrong with my ModelTable setup. Any help would be greatly appreciated.
package t1data;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.*;
import javax.swing.border.EmptyBorder;
import java.io.*;
import javax.swing.table.*;
public class T1Data extends JPanel implements ActionListener {
public T1Data() {
super(new BorderLayout(3,3));
JTable Table = new JTable(new MyModel());
Table.setPreferredScrollableViewportSize(new Dimension(700, 70));
Table.setFillsViewportHeight(true);
JPanel ButtonOpen = new JPanel( new FlowLayout(FlowLayout.CENTER) );
JButton OpenFile = new JButton("Open");
JButton SaveFile = new JButton("Save");
ButtonOpen.add(OpenFile);
add(ButtonOpen, BorderLayout.SOUTH);
OpenFile.addActionListener(this);
SaveFile.addActionListener(this);
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(Table);
//Add the scroll pane to this panel.
add(scrollPane, BorderLayout.CENTER);
// add a nice border
setBorder(new EmptyBorder(5,5,5,5));
}
public void actionPerformed (ActionEvent Event) {
JFileChooser fc = new JFileChooser();
boolean pressed = true;
// if (Event.getSource() == OpenFile) {
if (pressed) {
int ReturnVal = fc.showOpenDialog(null);
// if (ReturnVal == JFileChooser.APPROVE_OPTION) {
CSVFile Rd = new CSVFile();
//ArrayList<String[]> Rs2 = new ArrayList<>();
MyModel NewModel = new MyModel();
File DataFile = fc.getSelectedFile();
ArrayList<String[]> Rs2 = Rd.ReadCSVfile(DataFile);
NewModel.AddCSVData(Rs2);
System.out.println ("Rows: " +NewModel.getRowCount());
System.out.println ("Cols: " +NewModel.getColumnCount());
}
}
// Method for reading CSV file
public class CSVFile {
private ArrayList<String[]> Rs = new ArrayList<>();
private String[] OneRow;
public ArrayList<String[]> ReadCSVfile (File DataFile) {
try {
BufferedReader brd = new BufferedReader (new FileReader(DataFile));
while (brd.readLine() != null) {
String st = brd.readLine();
OneRow = st.split(",|\\s|;");
Rs.add(OneRow);
System.out.println (Arrays.toString(OneRow));
} // end of while
} // end of try
catch (Exception e) {
String errmsg = e.getMessage();
System.out.println ("File not found:" +errmsg);
} // end of Catch
return Rs;
}// end of ReadFile method
}// end of CSVFile class
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("T1Data");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
T1Data newContentPane = new T1Data();
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
class MyModel extends AbstractTableModel {
private String[] columnNames = { "1", "2", "3", "4", "5", "6"};
private ArrayList<String[]> Data = new ArrayList<>();
public void AddCSVData(ArrayList<String[]> DataIn) {
this.Data = DataIn;
this.fireTableDataChanged();
}
@Override
public int getColumnCount() {
return columnNames.length;//length;
}
@Override
public int getRowCount() {
return Data.size();
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public Object getValueAt(int row, int col)
{
return Data.get(row)[col];
}
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
// T1Data.createAndShowGUI();
}
}
(I've used your naming convetions, but you should read my comment above regarding the Java naming conventions for variables and classes).
You create a table pass a new MyModel
to the constructor:
JTable Table = new JTable(new MyModel());
Later you create a (separate) new MyModel
in actionPerformed()
:
MyModel NewModel = new MyModel();
File DataFile = fc.getSelectedFile();
ArrayList<String[]> Rs2 = Rd.ReadCSVfile(DataFile);
NewModel.AddCSVData(Rs2);
The problem, is that you never call table.setModel(NewModel)
.
To solve this problem, store the table variable as a field in your T1Data
class so you can refer to it later:
private final JTable table;
...
public T1Data() {
super(new BorderLayout(3,3));
this.table = new JTable(new MyModel());
this.table.setPreferredScrollableViewportSize(new Dimension(700, 70));
this.table.setFillsViewportHeight(true);
And set the model in actionPerformed()
:
this.table.setModel(NewModel);
这篇关于从CSV文件读取数据并将其显示在JTable中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!