dalvarezmartinez1
dalvarezmartinez1

Reputation: 1405

Edit JTable cell, as a JTree node

My goal is to use a JTable as a JTree node, and be able to edit the cells in the JTable by double clicking them. The rendering works well (Jtable as a Jtree Node), but I have no idea how to edit a single cell in the table. If I set the tree to be editable, I can edit the nodes using double click, but I want to edit cells by themselves, because the user might seem reluctant to maintaining the "%" in front of the numbers I use for rendering. If the tree is not set to be editable double click does nothing. Is there an easy way to accomplish this?

public class TreeWithCellRenderer {

static class MyCellRenderer implements TreeCellRenderer {
    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded,
            boolean leaf, int row, boolean hasFocus) {

        String command = (String) ((DefaultMutableTreeNode) value).getUserObject();
        final String[] params = command.split("%");
        JTable table = new JTable();

        table.setModel(new DefaultTableModel() {
            private static final long serialVersionUID = 1L;

            @Override
            public int getRowCount() {
                return 1;
            }

            @Override
            public int getColumnCount() {
                return params.length;
            }

            @Override
            public Object getValueAt(int row, int column) {
                return params[column];
            }
        });
        return table;
    }
}

private static void createAndShowGUI() {
    // Create and set up the window.
    JFrame frame = new JFrame("JTreeTutorial");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Tree components
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
    DefaultMutableTreeNode cmd1 = new DefaultMutableTreeNode("name %1");
    DefaultMutableTreeNode cmd2 = new DefaultMutableTreeNode("name %1 %2");
    root.add(cmd1);
    root.add(cmd2);

    JTree jTree = new JTree(root);
    //Don't like it too much, as it makes you edit the whole node, not cells
    //jTree.setEditable(true);
    jTree.setCellRenderer(new MyCellRenderer());
    JScrollPane scroolPane = new JScrollPane(jTree);
    frame.add(scroolPane);

    // Display the window.
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    createAndShowGUI();
}

}

Upvotes: 0

Views: 1390

Answers (2)

Denis Zaikin
Denis Zaikin

Reputation: 579

You should add method isCellEditable for your data model. Otherwise your table not editable.

It may looks like this:

@Override
public boolean isCellEditable(int row, int col) 
{
    return col >= 0;
}

Upvotes: 0

Related Questions