简体   繁体   English

JTable 没有显示任何信息。 从文本文件中读取并将其添加到 DefaultTableModel

[英]JTable not showing any information. Reading from a text file and adding it to a DefaultTableModel

I am working on a Java Swing project and I am trying to understand how to use JTable .我正在开发一个 Java Swing 项目,我正在尝试了解如何使用JTable

I have a text file with a list of user information which is all separated by a comma without spaces.我有一个包含用户信息列表的文本文件,这些信息都用逗号分隔,没有空格。 I am trying to get this information to be displayed in a table, however, when I run the form the table, it remains blank and never shows anything.我试图让这些信息显示在表格中,但是,当我运行表格时,它保持空白并且从不显示任何内容。

Here is my code:这是我的代码:

private JTable listUsersTable;

// ...

String[] columnNames = {"USERNAME", "NAME", "SURNAME", "AGE", "SEX", "SITE"};

// Creates a table with the column names and zero rows.
DefaultTableModel model = new DefaultTableModel(columnNames, 0);

try {
    BufferedReader reader = new BufferedReader(new FileReader("userArchive.txt"));

    // Reads each line in the file "userArchive.txt", separates the data, and puts them into the table.
    String line = reader.readLine();

    while (line != null) {
        String[] lineSplit = line.split(",");
        model.addRow(lineSplit);
        line = reader.readLine(); // Goes to the next line in the file.
    }
    reader.close();

    listUsersTable = new JTable(model);

} catch (FileNotFoundException e5) {
    e5.printStackTrace();
} catch (IOException ex) {
      ex.printStackTrace();
}

And here is my current JTable layout & settings using intelliJ's GUI designer:这是我当前使用 intelliJ 的 GUI 设计器的 JTable 布局和设置:

Image of my intelliJ GUI designer setup and the JTable in question.我的 intelliJ GUI 设计器设置和有问题的 JTable 的图像。 (The JTable in the image is called verUsuariosTable however in the code this is called listUsersTable . This is because I am writing my code in Spanish but translating everything to ask the question). (图像中的 JTable 称为verUsuariosTable但在代码中称为listUsersTable 。这是因为我正在用西班牙语编写代码,但要翻译所有内容以提出问题)。

I needed to include JScrollPane to the code.我需要在代码中包含JScrollPane This link shows completely what is needed to work with text files and JTables.此链接完全显示了使用文本文件和 JTable 所需的内容。 ( How do I read separate parts from a txt File to show in Java GUI? ). 如何从 txt 文件中读取单独的部分以在 Java GUI 中显示? )。

I needed to add我需要添加

listUsersTable.setPreferredScrollableViewportSize(listUsersTable.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(listUsersTable);

and then add the scrollPane to the panel I was working with using然后将 scrollPane 添加到我正在使用的面板中

currentPanel.add(scrollPane);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM