1) how to add simple node (without check box control) in Jtree.
2) Or how to add Check Box node(with check box control) in Jtree.
3) all node is add in seam Tree using java swing.
4) Please suggest me for this task .
following is code sample :
public class DynamicTreeView extends JFrame implements ActionListener, MouseListener {
private JTree tree;
private JTextField textBox;
private JButton btnCreateNode;
private JCheckBox chkNode, ch1;
private JScrollPane ScrollPan;
private JPanel pane, pane1;
private DefaultTreeModel model;
private JCheckBox check;
int hotspot;
public DynamicTreeView() {
hotspot = new JCheckBox().getPreferredSize().width;
pane = new JPanel();
textBox = new JTextField(10);
btnCreateNode = new JButton("Create Node");
chkNode = new JCheckBox("Has CheckBox");
pane.add(chkNode);
pane.add(textBox);
pane.add(btnCreateNode);
btnCreateNode.addActionListener(this);
this.addMouseListener(this);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Java Tree Example");
tree = new JTree(root);
model = (DefaultTreeModel) tree.getModel();
ScrollPan = new JScrollPane(tree);
getContentPane().add(ScrollPan, BorderLayout.WEST);
getContentPane().add(pane, BorderLayout.CENTER);
}
public static void main(String args[]) {
DynamicTreeView frame = new DynamicTreeView();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (btnCreateNode.equals(e.getSource())) {
if (chkNode.isSelected() == true) {
ch1 = new JCheckBox(textBox.getText());
TreeCellRenderer render = new TreeCellRenderer() {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
Component returnValue;
if ((value != null) && (value instanceof DefaultMutableTreeNode)) {
Object userObject = ((DefaultMutableTreeNode) value).getUserObject();
ch1.setText(textBox.getText());
ch1.setSelected(selected);
}
returnValue = ch1;
return returnValue;
}
};
JOptionPane.showMessageDialog(this, ch1);
JTree t = new JTree();
t.setCellRenderer(render);
MutableTreeNode newNode = new DefaultMutableTreeNode(t);
TreePath path = tree.getSelectionPath();
MutableTreeNode node = (MutableTreeNode) path.getLastPathComponent();
} else {
CheckRenderer cr = new CheckRenderer();
cr.setNode(new DefaultMutableTreeNode(textBox.getText()));
model = (DefaultTreeModel) tree.getModel();
TreePath path = tree.getSelectionPath();
MutableTreeNode newNode = cr.getNode();
MutableTreeNode node = (MutableTreeNode) path.getLastPathComponent();
model.insertNodeInto(newNode, node, node.getChildCount());
}
}
SwingWorker sw = new SwingWorker() {
@Override
protected Object doInBackground() throws Exception {
((DefaultTreeModel) tree.getModel()).reload();
tree.revalidate();
tree.repaint();
ScrollPan.setViewportView(tree);
return null;
}
};
sw.execute();
}
}