Table of Contents
Overview
Main knowledge points
The main method of CsvReader
Example - Read a csv file on the local desktop
Home Java javaTutorial How to import CSV files into JTable for display using Java

How to import CSV files into JTable for display using Java

Apr 21, 2023 pm 11:34 PM
java csv jtable

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<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;
    }
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!

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 admin@php.cn

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles