首页 > 代码库 > java 树与表心得
java 树与表心得
在定制表与树是 模型很重要,定义是千万不要模糊
如:
DefaultTableModel mode = new DefaultTableModel();
JTable table = new JTable(mode);
在接下来的树与表相对应的关系中很难一一对应;而且不利于在JSCrollPane中的显示。
下面这个就是一个很好的方法 ,而且方便树与表的相互对应,且很容易实现:
DefaultTableModel mode;
JTable table = new JTable();
mode = (DefaultTableModel mode)table.getMOdel();
在接下来的程序中 只需用到模型即可改变表中的格式;
例子:
package TableTree;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.*;
public class TableTree extends JPanel implements TreeSelectionListener {
/**
* @param args
*/
JPanel myJPanel;
JTable table;
JScrollPane myJSTree,myJSTable;
JTree myJTree;
DefaultMutableTreeNode root,temp;
Object NodePath;
DefaultTreeModel rs;
String StrPath;
int row,col;
TreeSelectionModel selectionModel;
DefaultTableModel model;
JFrame myJFrame;
public TableTree(){
super();
myJFrame = new JFrame("TreeTable");
table = new JTable();
model = (DefaultTableModel)table.getModel();
this.setLayout(new BorderLayout());
this.add(table,BorderLayout.CENTER);
myJSTable = new JScrollPane(this);
myJFrame.add(myJSTable,BorderLayout.CENTER);
root = new DefaultMutableTreeNode("root");
temp = new DefaultMutableTreeNode("father");
temp.add(new DefaultMutableTreeNode("chirld1"));
temp.add(new DefaultMutableTreeNode("chirld2"));
temp.add(new DefaultMutableTreeNode("chirld3"));
temp.add(new DefaultMutableTreeNode("chirld4"));
temp.add(new DefaultMutableTreeNode("chirld5"));
root.add(temp);
rs = new DefaultTreeModel(root);
myJTree = new JTree(rs);
selectionModel = myJTree.getSelectionModel();
selectionModel.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
myJTree.addTreeSelectionListener(this);
myJSTree = new JScrollPane(myJTree);
myJFrame.add(myJSTree,BorderLayout.WEST);
myJFrame.setSize(550,400);
myJFrame.setLocation(150, 150);
myJFrame.setVisible(true);
myJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
java 树与表心得