我知道这是一个简单而愚蠢的问题,因为我是新手,所以不知道如何链接。
我正在尝试获取node value(带有路径的文件),并使用JButton-“添加文件”将节点值推送到JTable中,到目前为止已经发布了代码,但并没有给出任何错误,但是没有执行我想要的操作,谢谢。
如何从一个函数到另一个函数获取节点值,谢谢
从JTree获取节点值
File root = new File(System.getProperty("user.home"));
FileTreeModel model = new FileTreeModel(root);
JTree tree = new JTree(model);
JScrollPane scrollpane = new JScrollPane(tree);
scrollpane.setBounds(10, 9, 304, 730);
frmViperManufacturingRecord.getContentPane().add(scrollpane);
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
File node = (File)e.getPath().getLastPathComponent();
//System.out.println("You selected " + node);
if (!node.isFile()) {
JFrame frame = new JFrame();
JOptionPane.showConfirmDialog(frame, "Please select the valid file to Add Files", "Not Valid File",JOptionPane.PLAIN_MESSAGE );
//if (result == JOptionPane.CANCEL_OPTION);
}
//else
}
});
尝试将节点值推入JTable
//table just below Add Files button
table_2 = new JTable();
table_2.setBounds(324, 43, 713, 121);
frmViperManufacturingRecord.getContentPane().add(table_2);
使用JButton
// Add files button
JButton btnAddFiles_1 = new JButton("Add Files");
btnAddFiles_1.setMnemonic('A');
btnAddFiles_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Object rowData[][] = { { "01.", node, }};
Object columnNames[] = { "Sl.no", "File name"};
JTable table = new JTable(rowData, columnNames);
}
});
btnAddFiles_1.setFont(new Font("Calibri", Font.BOLD, 12));
btnAddFiles_1.setBounds(324, 9, 89, 23);
frmViperManufacturingRecord.getContentPane().add(btnAddFiles_1);
最佳答案
这里:
btnAddFiles_1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
Object rowData[][] = { { "01.", node, }};
Object columnNames[] = { "Sl.no", "File name"};
JTable table = new JTable(rowData, columnNames); // new JTable that is not placed in the content pane
}
});
不要重新创建表本身,因为已经创建并放置了
table_2
。而是更新其表模型。例如:btnAddFiles_1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
Object rowData[][] = { { "01.", node, }};
Object columnNames[] = { "Sl.no", "File name"};
table_2.setModel(new DefaultTableModel(rowData, columnNames));
}
});
旁注
关于这条线:
table_2.setBounds(324, 43, 713, 121);
Swing被设计为与LayoutManagers一起使用,不建议使用诸如
setBounds(...)
,setLocation(...)
和setXxxSize(...)
之类的方法。见Laying Out Components Within a Container另外(感谢@mKorbel的评论):
frmViperManufacturingRecord.getContentPane().add(table_2);
表格应该放在
JScrollPane
中,就像您的树一样:JScrollPane scrollPane = new JScrollPane(table_2);
frmViperManufacturingRecord.getContentPane().add(scrollPane);