Home > Java > Java Tutorial > body text

How to import CSV files into JTable for display using Java

WBOY
Release: 2023-04-21 23:34:06
forward
777 people have browsed it

Overview

Main knowledge points

a.SwingNode class: Encapsulates the Java swing component into a JavaFX Node, so that Java Swing can be nested with JavaFX. JavaSwing is ugly. , but the operation is simple. The table components of JavaFX (TableView, etc.) are a bit complicated, so choose nested JavaSwing to use it. Just be ugly

b.javacsv-2.0.jar: Used to read csv through file address file and can perform a series of operations. Although it will no longer be updated after 2008, it is enough to operate a csv file.

c.FileChoose class: A file selector for JavaFX that can open the local resource manager. Whether the UI is beautiful or not depends on your system version.

d.CsvReader class: A tool class under the javacsv-2.0.jar package, mainly used to operate csv files

e.JTable class: Create a JTable instance to make csv files After opening the display, you need to pay attention to the order of parameters. The table content is a two-dimensional array, and the header is a one-dimensional array

JTable table = new JTable(表格内容,表头);
Copy after login

f. Store the one-digit array into the one-dimensional array:

String[][] arr = new String[10][];//开辟一个10行的二维数组
String[] row1 = {"id","name","sex","age"};
 
arr[0] = row1;//存进二维数组
Copy after login

g. JTable does not display the header: you need to put the JTable object into a Pane

JTable table = new JTable(表内容,表头);
JScrollPane jScrollPane = new JScrollPane(table);
 
SwingNode swingNode = new SwingNode();
swingNode.setContent(jScrollPane);//使用swingNode封装swing组件,就可以在Javafx中用了
Copy after login

The main method of CsvReader

  • new CsvReader(String filePath) initialization construction When you need to pass in a local csv file address

  • boolean readHeaders() read the header and skip

  • String[] getHeaders() Get the csv file header (very strange, you need to call the readHeaders() method before you can get it, otherwise a null pointer exception will be reported)

That's it:

CsvReader reader = new CsvReader("xxx.csv");
reader.readHeaders(); //没有这句话,执行下面会报错
String[] head = reader.getHeaders();
Copy after login
  • boolean readRecord() reads a line of csv content. As long as you call it, the next time you call it, it will switch to the next line of csv. Usually we use a while loop to operate all the content line by line in time

  • String getRawRecord() Read a row of data

while (reader.readRecord()){
    System.out.println(reader.getRawRecord());//输出一行内容
}
Copy after login

Example - Read a csv file on the local desktop

@Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("文件选择器");
        primaryStage.setHeight(600);
        primaryStage.setWidth(800);
 
        final FileChooser fileChooser = new FileChooser();
 
        //设置打开资源管理器后的文件过滤
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("All Images","*.*"),
                new FileChooser.ExtensionFilter("PNG","*.png"),
                new FileChooser.ExtensionFilter("MP4","*.mp4"),
                new FileChooser.ExtensionFilter("CSV","*.csv")
        );
 
        final Button open = new Button("打开文件");
 
        final GridPane inputGridPane = new GridPane();//创建格子布局面板
        GridPane.setConstraints(open,0,0);//第0行0列
 
        inputGridPane.setHgap(6.0);//设置水平间距
        inputGridPane.setVgap(6.0);//设置垂直间距
        inputGridPane.getChildren().addAll(open);//添加按钮
 
        final Pane rootGroup = new VBox(12);//创建一个垂直盒子布局器
        rootGroup.getChildren().addAll(inputGridPane);//把格子面板放进来
        rootGroup.setPadding(new Insets(12,12,12,12));
 
        primaryStage.setScene(new Scene(rootGroup));
        primaryStage.show();
 
//设置点击-打开文件-的动作事件
open.setOnAction(event -> {
            File file = fileChooser.showOpenDialog(primaryStage);//在当前窗口打开文件选择器
            if (file != null){
                try {
                    FileInputStream inputStream = new FileInputStream(file);
                    BufferedInputStream stream = new BufferedInputStream(inputStream);
                    String fileName = file.getName();
                    String filePath = file.getAbsolutePath();
                    System.out.println("文件路径 = "+filePath);
                    try {
                        CSVDemo.read(filePath);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }    
                    //封装JTable,使得JTable和Javafx嵌套在一起    
                    SwingNode swingNode = new SwingNode();
                    try {
                        JTable table = read(filePath);
                        JScrollPane jScrollPane = new JScrollPane(table);
                        swingNode.setContent(jScrollPane);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                //设置JTable打开后表格的相对位置
                GridPane.setConstraints(swingNode,0,1);
                    inputGridPane.getChildren().add(swingNode);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
}
//读取csv文件并把它读取到JTable中返回
public static JTable read(String filePath) throws IOException {
 
            CsvReader reader = new CsvReader(filePath);
            reader.readHeaders();//跳过表头
            String[] head = reader.getHeaders();
 
            List list = new ArrayList<>();
            String s = reader.getRawRecord();
            System.out.println("表头 "+s);
            String[] r1 = dataToArray(s);
//            list.add(r1);
 
            while (reader.readRecord()) {
                System.out.println(reader.getRawRecord());
                list.add(dataToArray(reader.getRawRecord()));
            }
        String[][] data = new String[list.size()][];
        System.out.println("一共"+list.size()+"行数据");
        for (int i = 0; i < data.length; i++) {
            data[i] = list.get(i);
        }
            JTable table = new JTable(data,head);
            return table;
 
    }
//将每一行的数据从String转为String数组
    public static String[] dataToArray(String row){
        String[] res = row.split(",");
        return res;
    }
Copy after login

Effect Display

How to import CSV files into JTable for display using Java

JScrollPane encapsulates JTable, SwingNode encapsulates JScrollPane

How to import CSV files into JTable for display using Java

The above is the detailed content of How to import CSV files into JTable for display using Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!