我有一个JTable,我试图用位于特定文件夹中的文件名来填充。

我可以加载JTable,看起来好像是从数据中填充它,但是JTable行中没有测试。

我可以告诉它正在加载文件,因为当我在文件夹中放置2个文件时,JTable在加载时会创建2行。我可以更改文件夹中的文件数,当我重新运行该程序时,它将加载确切的行数作为文件夹中的文件。

有任何想法吗?我使用了这种方法来填充其他几张表,它们似乎可以工作,所以我对为什么不这样做感到困惑。

package testTable;

import java.awt.BorderLayout;


public class main extends JFrame {

public JPanel contentPane;
public JTable table;
public DefaultTableModel rulesModel;


/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                main frame = new main();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
@SuppressWarnings("serial")
public main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);

    JScrollPane scrollPane = new JScrollPane();
    GroupLayout gl_contentPane = new GroupLayout(contentPane);
    gl_contentPane.setHorizontalGroup(
        gl_contentPane.createParallelGroup(Alignment.TRAILING)
            .addGroup(Alignment.LEADING, gl_contentPane.createSequentialGroup()
                .addContainerGap()
                .addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 414, Short.MAX_VALUE))
    );
    gl_contentPane.setVerticalGroup(
        gl_contentPane.createParallelGroup(Alignment.LEADING)
            .addGroup(gl_contentPane.createSequentialGroup()
                .addContainerGap()
                .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 187, GroupLayout.PREFERRED_SIZE)
                .addContainerGap(54, Short.MAX_VALUE))
    );




    rulesModel = new DefaultTableModel();
    rulesModel.setColumnIdentifiers(new String[] {"File Name"});
    table = new JTable(rulesModel) {
        public boolean isCellEditable(int row, int column) {
            return false;
        }
        public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            return (Component) null;
        }
    };


    File folder = new File("C:\\Scripts\\new\\files\\folder\\");
    File[] listOfFiles = folder.listFiles();

    for (File file : listOfFiles) {
        if (file.isFile()) {
            String filename = file.getName();

            rulesModel.addRow(new String[] {filename});
            System.out.println(filename);
        }
    }




    table.setModel(rulesModel);
    scrollPane.setViewportView(table);
    contentPane.setLayout(gl_contentPane);
}


}

最佳答案

这让您感到困惑:

 public Component prepareRenderer(TableCellRenderer renderer, int row,
       int column) {
    return (Component) null;
 }


它会占用JTable的所有单元格渲染器,将其扔到一边,从而保证该表不会显示任何信息。因此,请摆脱这种错误的覆盖。

尽管这确实引出了一个问题:
为什么还要在此代码,因为可以确保完全不显示任何内容?为什么要摆脱单元格渲染器?

09-04 02:56
查看更多