首页 > 解决方案 > 用户界面中的 JTable

问题描述

我需要帮助了解如何实现 JTable。当给定标题名称和数据时,我的 JTable 没有显示,我尝试了 pack()(使我的所有内容都消失了,但我的菜单消失了),我尝试了 setFillsViewportHeight(true),但没有任何更新。任何帮助或指导将不胜感激。

// Main
public static void main(String[] args) {
    Main window = new Main("A Project");
    window.setBounds(30, 30, 700, 500);
    window.setVisible(true);
}


// Displays a box with a menu bar that has file and about options(code not shown):

public Main(String title) {
    JMenuBar menuBar = new JMenuBar(); // Window menu bar
    setTitle(title);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setJMenuBar(menuBar); // Add the menu bar to the window
}

// This section of code is inside action listener when you click menu bar's file then load a file:
// Nothing appears:

String[] columnNames = {"ID","First Name","Last Name","Program","Level","USERNAME"};
        ArrayList[][] data = loadFileRoster.getRosterData();
        JTable table = new JTable(data,columnNames);
        JScrollPane scrollPane = new JScrollPane(); 
        table.add(scrollPane);
        table.setVisible(true);

标签: javaswingjtable

解决方案


    ArrayList[][] data = loadFileRoster.getRosterData();
    JTable table = new JTable(data,columnNames);

我不知道您可以使用包含您的数据的 ArrayList 创建一个 JTable(除非是 JDK 14 中的新功能)

    JScrollPane scrollPane = new JScrollPane(); 
    table.add(scrollPane);

您不会将滚动窗格添加到表中。您将 a 添加JTableJViewporta 中JScrollPane。这是通过使用:

    JScrollPane scrollPane = new JScrollPane( table );

然后将滚动窗格添加到框架中。

    table.setVisible(true);

Swing 组件默认是可见的。setVisible(true) 是不必要的。

阅读 Swing 教程中有关如何使用表格的部分以获取工作示例。

下载示例并修改它们。他们将向您展示如何更好地构建您的代码。


推荐阅读