从JTree事件获取节点值到另一个事件按钮按下

时间:2014-11-27 16:34:49

标签: java swing user-interface jbutton

基本上想要从JTree中选择节点并使用JButton推送节点值JTable for example:

我能够从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 );
            }
        }
    });

按钮事件:

// Add files button
    JButton btnAddFiles_1 = new JButton("Add Files");
    btnAddFiles_1.setMnemonic('A');
    btnAddFiles_1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            System.out.println("You...."  );

            final String[] columnNames = {"Sl.no.", "File Name",};
            final String[][] data = {
                    {"01.", node, },};
            table_2.setModel(new DefaultTableModel(data, columnNames));
            frmViperManufacturingRecord.getContentPane().add(table_2);
            table_2.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            table_2.getColumnModel().getColumn(0).setPreferredWidth(113);
            table_2.getColumnModel().getColumn(1).setPreferredWidth(600);
            JScrollPane scrollPane = new JScrollPane(table_2);
            scrollPane.setBounds(324, 43, 713, 121);
            frmViperManufacturingRecord.getContentPane().add(scrollPane);
        }
    });
    btnAddFiles_1.setFont(new Font("Calibri", Font.BOLD, 12));
    btnAddFiles_1.setBounds(324, 9, 89, 23);
    frmViperManufacturingRecord.getContentPane().add(btnAddFiles_1);

1 个答案:

答案 0 :(得分:2)

在这一行:

tree.addTreeSelectionListener(new TreeSelectionListener() {
    @Override // don't forget @Override annotation
    public void valueChanged(TreeSelectionEvent e) {
        File node = (File)e.getPath().getLastPathComponent(); // Look here!
        ...
    }
});

变量nodevalueChanged()方法的局部变量,它也在Anonymous inner class范围内定义,使其无法从外部访问:

btnAddFiles_1.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent ae) {
        ...
        final String[][] data = {{"01.", node, }}; // node is not accessible here
        ...
    }
});

如果要在其他任何地方使用选定的node,则需要更宽的范围(即:封闭类的类字段)或创建实现TreeSelectionListener接口的非匿名类并提供适当的getter到所选节点。