我有一个 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 存在的任何单元格渲染器,将其扔到一边,从而保证表不会显示任何信息。因此,摆脱这个错误的覆盖。
尽管这确实引出了一个问题:
为什么这段代码甚至在那里,因为它保证确保没有任何显示?为什么要摆脱单元格渲染器?
关于Java JTable 未填充 DefaultTableModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27323658/