search
HomeJavajavaTutorialHow to import CSV files into JTable for display using Java

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(表格内容,表头);

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;//存进二维数组

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中用了

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();
  • 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());//输出一行内容
}

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<String []> 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;
    }

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!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)