亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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(表格內(nèi)容,表頭);

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

String[][] arr = new String[10][];//開辟一個10行的二維數(shù)組
String[] row1 = {"id","name","sex","age"};
 
arr[0] = row1;//存進(jìn)二維數(shù)組

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

JTable table = new JTable(表內(nèi)容,表頭);
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(); //沒有這句話,執(zhí)行下面會報錯
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());//輸出一行內(nèi)容
}

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();
 
        //設(shè)置打開資源管理器后的文件過濾
        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();//創(chuàng)建格子布局面板
        GridPane.setConstraints(open,0,0);//第0行0列
 
        inputGridPane.setHgap(6.0);//設(shè)置水平間距
        inputGridPane.setVgap(6.0);//設(shè)置垂直間距
        inputGridPane.getChildren().addAll(open);//添加按鈕
 
        final Pane rootGroup = new VBox(12);//創(chuàng)建一個垂直盒子布局器
        rootGroup.getChildren().addAll(inputGridPane);//把格子面板放進(jìn)來
        rootGroup.setPadding(new Insets(12,12,12,12));
 
        primaryStage.setScene(new Scene(rootGroup));
        primaryStage.show();
 
//設(shè)置點擊-打開文件-的動作事件
open.setOnAction(event -> {
            File file = fileChooser.showOpenDialog(primaryStage);//在當(dāng)前窗口打開文件選擇器
            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();
                    }
                //設(shè)置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()+"行數(shù)據(jù)");
        for (int i = 0; i < data.length; i++) {
            data[i] = list.get(i);
        }
            JTable table = new JTable(data,head);
            return table;
 
    }
//將每一行的數(shù)據(jù)從String轉(zhuǎn)為String數(shù)組
    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 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Google Chrome cannot open local files Google Chrome cannot open local files Aug 01, 2025 am 05:24 AM

ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor

Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

See all articles