社区
Java SE
帖子详情
哪位SWING高手知道:jTree怎样动态的加入node?????????????????????
richzhang
2003-10-16 01:04:27
比如在JComboBox中选择一项,JTree对象中就在指定的位置加入一个node?
我用DefaultMutableTreeNode 好像只能在运行前加入?
谢谢指点?
...全文
62
3
打赏
收藏
哪位SWING高手知道:jTree怎样动态的加入node?????????????????????
比如在JComboBox中选择一项,JTree对象中就在指定的位置加入一个node? 我用DefaultMutableTreeNode 好像只能在运行前加入? 谢谢指点?
复制链接
扫一扫
分享
转发到动态
举报
写回复
配置赞助广告
用AI写文章
3 条
回复
切换为时间正序
请发表友善的回复…
发表回复
打赏红包
孙亖
2003-12-09
打赏
举报
回复
good
pxboy
2003-10-17
打赏
举报
回复
TreeNode parentNode = (TreeNode) (parentPath.getLastPathComponent());
你只要指定父节点就行了,这里是当前选择的节点
treeModel.insertNodeInto(newNode, parentNode, parentNode.getChildCount());
parentNode.getChildCount()是插入节点的位置
pxboy
2003-10-16
打赏
举报
回复
DefaultTreeModel treeModel = (DefaultTreeModel)jTree.getModel();
TreeNode parentNode = (TreeNode) (parentPath.getLastPathComponent());
TreeNode newNode = new TreeNode("新节点");
treeModel.insertNodeInto(newNode, parentNode, parentNode.getChildCount());
swing
界面设计之
JTree
目录 目录 1 (一) Spring 开发
Swing
GUI 简介——依赖注入和富客户机 5 关于本教程 5 前提条件 6 Spring 和依赖注入概述 7 什么是 Spring 框架? 7 什么是依赖注入? 7 环境设置 7 选择编译环境 7 设置 Ant 8 通过 Ant 自动下载依赖软件 10 设置 Maven 10 通过 Maven 自动下载依赖软件 12 设置 Eclipse 13 下载依赖的 JAR 文件并在 Eclipse 的 classpath 中定义这种依赖性 15 创建 to-do 列表:基本的
Swing
和 Spring 应用程序设置 17 创建 MainFrame、Launcher 和 ToDo 类 17 创建 Spring app-context.xml bean 定义文件 19 运行应用程序 20 定义 bean 属性 21 创建 to-do 列表:创建一个可重用组件并在表中显示数据 23 创建一个可重用的面板 23 将 bean 组合在一起 24 添加一个表并重用这个面板 26 定义表模型 28 显示列表中的项 29 创建 to-do 列表:完成 —— 按钮和监听程序 31 创建按钮和监听程序 32 组合按钮和监听程序 35 Spring Rich Client Project 37 Spring Rich Client Project 概述 37 结束语 38 (二) 适用于各类
Swing
应用的通用数据验证模块 39 项目创建好后,
加入
类库: 41 然后写一个persistence bean: 41 Java代码 41 我称这个类为HibernateValidationUI,代码如下: 43 Java代码 43 类中用到的Java2DIconFactory代码如下: 47 Java代码 47 Factory类 49 Java代码 49 最后,我们可以编写一个Demo application来看看效果如何,代码如下: 51 Java代码 51 总结: 55 (三) 对
JTree
从创建到使用详解 56 (四)
JTree
的使用方法 57
JTree
Demo.java源程序 57 经验汇总 60 1. 初始化 60 2. 三个经常使用的取值函数 60 3. 根据
node
得到path: 60 4. 根据Path展开到该节点 60 5. 根据path设定该节点选定 61 6. 选中节点的方法 61 7. 滚动到可见位置 61 8. 给
JTree
添加右键弹出菜单 61 9. 关于
JTree
的展开 61 10. 如何遍历
JTree
62 (五)
JTree
右键菜单实现编辑、添加、删除节点 63 Test.java源代码 63 (六) 功能齐全的
JTree
例子 66 TreeEditTest.java源代码 66 (七)
JTree
控件的使用 70 构造函数: 70 TreeModel接口 70 DefaultTreeModel缺省版本 71 Tree
Node
接口 71 TreeExpansionListener接口 71 TreeCellRenderer 72 例子: 73 (八) 如何为
JTree
添加右键菜单? 75 (九) 如何使JTextArea随着窗体的变化自动调整大小 76 TextAreaTest源代码 76 (十) JAVA
swing
编程
JTree
实现系统目录 77 FileTree1.java源代码 77 (十一) Java
Swing
中的
JTree
模型 85
Swing
.tree包中的主要类名称实现 85 1. 构建树模型 86 2. 树结点 86 树结构详细类图 86 2.1 Tree
Node
接口 86 2.2 MutableTree
Node
接口 87 2.3 DefaultMutableTree
Node
类 88 3. 编辑树 88 3.1获得结点路径 88 3.2编辑结点 88 3.3视图显示 89 4. 查找树 89 5. 绘制结点 90 (十二)
JTree
鼠标左键的双击事件选用那个监听器 91 MouseDemo.java源代码 92 (十三)
JTree
92
JTree
的构造函数: 93
JTree
DefaultDemo.java源代码 93 (十四)
JTree
应用 96 Frame1.java源代码 96 MyDefaultTreeCellRenderer.java源代码 98 (十五)
JTree
控件 100 树和节点的基本概念 100 有关树
JTree
的类和接口 100 代码实例:构建一棵树 101 相关语句解释 101 (十六)
JTree
应用示例——文件路径 103 AnimatedIconTreeExample.java源代码 103 //内部类
Node
ImageObserver.java源代码 105 //Icon
Node
Renderer.java源代码 106 //Icon
Node
.java源代码 107 (十七)
Swing
学习笔记 108
Swing
API 包括18个公共包: 108 例程1.1 HelloWorld
Swing
.java 109 例程2.2 HelloWorldJFrame.java 110 (十八)
动态
加载文件树的java程序 111 FileSystemTree.java源代码 112 //内部类 TreeWillExpandListenerImp.java 114 (十九) 向 Java 应用程序伸出援助之手——用 JavaHelp 2.0 构建下一个 Java 应用程序的帮助系统 115 入门 116 使用 HelpSet 117 HelpSet 数据文件 118 helpset 文件 118 maps 部分 119 view 部分 119 presentation 部分 120 implementation 部分 121 map 文件 121 导航文件 121 TOC 122 Index 122 Glossary 123 Favorites 123 主题文件 123 在 Java 应用程序中调用 JavaHelp 124 自定义外观 125 配置图标 125 基于文字的标签还是基于图像的标签? 125 要工具栏还是不要工具栏? 125 设置字体 126 使用展示窗口 127
标签 128 四种 activator 129 添加内容敏感的帮助 130 窗口级帮助 131 字段级帮助 131 屏幕级帮助 133 添加嵌入帮助 135 添加搜索功能 136 停用词 137 自定义停用词列表 137 合并 helpset 138 静态和
动态
合并 139 添加轻量级组件 141 基于服务器的帮助 144 设置 144 JavaHelp 服务器 bean 144 JavaScript 文件 145 JSP 文件 145 测试服务器端帮助 148 结束语 149
jtable增删改查和
jtree
连接
package BookTest; import java.awt.*; import java.awt.event.*; import java.util.AbstractQueue; import java.util.Vector; import javax.
swing
.*; import javax.
swing
.table.*; import javax.
swing
.tree.DefaultMutableTree
Node
; import javax.
swing
.tree.DefaultTreeCellRenderer; import javax.
swing
.tree.DefaultTreeModel; import javax.
swing
.tree.TreeSelectionModel; import javax.
swing
.event.*; import javax.
swing
.table.TableColumnModel; //import DbHelp.OperatorJobs; import Dao.ArrayBook; public class Test extends JFrame { public JPanel jp=null; public String aa; //JTable jTable1 = new JTable(); public JTable jTable1=null; private
JTree
jTree
1; DefaultTableModel mode; private JScrollPane scrollPane = null; DefaultMutableTree
Node
node
; JButton[] btn={new JButton("增加"),new JButton("删除"),new JButton("修改"),new JButton("查询"),new JButton("重置")}; public JTextField[] txt ={new JTextField(),new JTextField(),new JTextField(),new JTextField(),new JTextField(),new JTextField()}; public String[] str1={"1","summer","boy","20","",""}; public String[] str2={"2","wulei","girl","19","",""}; public String[] str3={"3","west","boy","20","",""}; public String[] str4={"4","fish","girl","18","",""}; public String[] str5={"5","youku","boy","21","",""}; public String[] str6={"6","aa","boy","21","",""}; public String[][] tempData1={str1,str2,str3,str4,str5,str6}; public String[] aa1={"1","summer","boy","20","123","123"}; public String[] aa2={"2","wulei","girl","19","123",""}; public String[] aa3={"3","west","boy","20","123",""}; public String[] aa4={"4","fish","girl","18","1",""}; public String[] aa5={"5","youku","boy","21","12",""}; public String[] aa6={"6","aa","boy","21","123",""}; public String[][] tempData4={aa1,aa2,aa3,aa4,aa5,aa6}; //设置表头数据 public String[] tempTitle={"ID","标题","内容","作者","时间","是否选中"}; //设置表格的数据集合 Vector v1=new Vector(); Vecto
swing
文件拖拽
实现文件的拖拽功能 import java.awt.AlphaComposite; import java.awt.Component; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.dnd.DnDConstants; import java.awt.dnd.DragGestureEvent; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DragSource; import java.awt.dnd.DragSourceDragEvent; import java.awt.dnd.DragSourceDropEvent; import java.awt.dnd.DragSourceEvent; import java.awt.dnd.DragSourceListener; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.dnd.DropTargetListener; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.
swing
.Icon; import javax.
swing
.JLabel; import javax.
swing
.
JTree
; import javax.
swing
.Timer; import javax.
swing
.event.TreeExpansionEvent; import javax.
swing
.event.TreeExpansionListener; import javax.
swing
.filechooser.FileSystemView; import javax.
swing
.tree.DefaultMutableTree
Node
; import javax.
swing
.tree.DefaultTreeCellRenderer; import javax.
swing
.tree.DefaultTreeModel; import javax.
swing
.tree.TreePath; class DragTree extends
JTree
implements DragGestureListener, DragSourceListener, DropTargetListener { /** * */ private static final long serialVersionUID = 1L; BufferedImage ghostImage; private Rectangle2D ghostRect = new Rectangle2D.Float(); private Point ptOffset = new Point(); private Point lastPoint = new Point(); private TreePath lastPath; private Timer hoverTimer; File
Node
source
Node
; public DragTree() { DragSource dragSource = DragSource.getDefaultDragSource(); dragSource.createDefaultDragGestureRecognizer(this, // component where // drag originates DnDConstants.ACTION_COPY_OR_MOVE, // actions this); // drag gesture recognizer setModel(createTreeModel()); addTreeExpansionListener(new TreeExpansionListener() { public void treeCollapsed(TreeExpansionEvent e) { } public void treeExpanded(TreeExpansionEvent e) { TreePath path = e.getPath(); if (path != null) { File
Node
node
= (File
Node
) path.getLastPathComponent(); if (!
node
.isExplored()) { DefaultTreeModel model = (DefaultTreeModel) getModel();
node
.explore(); model.
node
StructureChanged(
node
); } } } }); this.setCellRenderer(new DefaultTreeCellRenderer() { public Component getTreeCellRendererComponent(
JTree
tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { TreePath tp = tree.getPathForRow(row); if (tp != null) { File
Node
node
= (File
Node
) tp.getLastPathComponent(); File f =
node
.getFile(); try { Icon icon = FileSystemView.getFileSystemView() .getSystemIcon(f); this.setIcon(icon); this.setLeafIcon(icon); this.setOpenIcon(icon); this.setClosedIcon(icon); this.setDisabledIcon(icon); } catch (Exception e) { e.printStackTrace(); } } return super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); } }); super.setScrollsOnExpand(true); new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this); // Set up a hover timer, so that a
node
will be automatically expanded // or collapsed // if the user lingers on it for more than a short time hoverTimer = new Timer(1000, new ActionListener() { public void actionPerformed(ActionEvent e) { if (lastPath == null) { return; } if (getRowForPath(lastPath) == 0) return; // Do nothing if we are hovering over the root
node
if (isExpanded(lastPath)) collapsePath(lastPath); else expandPath(lastPath); } }); hoverTimer.setRepeats(false); // Set timer to one-shot mode this.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { int code = e.getKeyCode(); int modifiers = e.getModifiers(); if (code == 'v' || code == 'V') { System.out.println("find v"); System.out.println("modifiers:" + modifiers + "\t" + ((modifiers & KeyEvent.CTRL_MASK) != 0)); } if ((modifiers & KeyEvent.CTRL_MASK) != 0 && (code == 'v' || code == 'V')) { Transferable tr = Toolkit.getDefaultToolkit() .getSystemClipboard().getContents(null); TreePath path = getSelectionPath(); if (path == null) { return; } File
Node
node
= (File
Node
) path.getLastPathComponent(); if (
node
.isDirectory()) { System.out.println("file cp"); try { List list = (List) (tr .getTransferData(DataFlavor.javaFileListFlavor)); Iterator iterator = list.iterator(); File parent =
node
.getFile(); while (iterator.hasNext()) { File f = (File) iterator.next(); cp(f, new File(parent, f.getName())); }
node
.reexplore(); } catch (Exception ioe) { ioe.printStackTrace(); } updateUI(); } } } }); } public void dragGestureRecognized(DragGestureEvent e) { // drag anything ... TreePath path = getLeadSelectionPath(); if (path == null) return; File
Node
node
= (File
Node
) path.getLastPathComponent(); source
Node
=
node
; // Work out the offset of the drag point from the TreePath bounding // rectangle origin Rectangle raPath = getPathBounds(path); Point ptDragOrigin = e.getDragOrigin(); ptOffset.setLocation(ptDragOrigin.x - raPath.x, ptDragOrigin.y - raPath.y); // Get the cell renderer (which is a JLabel) for the path being dragged int row = this.getRowForLocation(ptDragOrigin.x, ptDragOrigin.y); JLabel lbl = (JLabel) getCellRenderer().getTreeCellRendererComponent( this, // tree path.getLastPathComponent(), // value false, // isSelected (dont want a colored background) isExpanded(path), // isExpanded getModel().isLeaf(path.getLastPathComponent()), // isLeaf row, // row (not important for rendering) false // hasFocus (dont want a focus rectangle) ); lbl.setSize((int) raPath.getWidth(), (int) raPath.getHeight()); // <-- // The // layout // manager // would // normally // do // this // Get a buffered image of the selection for dragging a ghost image this.ghostImage = new BufferedImage((int) raPath.getWidth(), (int) raPath.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE); Graphics2D g2 = ghostImage.createGraphics(); // Ask the cell renderer to paint itself into the BufferedImage g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 0.5f)); // Make the image ghostlike lbl.paint(g2); g2.dispose(); // this.getGraphics().drawImage(ghostImage, e.getDragOrigin().x, // e.getDragOrigin().y, this); e.startDrag( null, // cursor ghostImage, new Point(5, 5), new StringSelection(getFilename()), // transferable this); // drag source listener } public void dragDropEnd(DragSourceDropEvent e) { ghostImage = null; source
Node
= null; } public void dragEnter(DragSourceDragEvent e) { } public void dragExit(DragSourceEvent e) { if (!DragSource.isDragImageSupported()) { repaint(ghostRect.getBounds()); } } public void dragOver(DragSourceDragEvent e) { } public void dropActionChanged(DragSourceDragEvent e) { } public String getFilename() { TreePath path = getLeadSelectionPath(); File
Node
node
= (File
Node
) path.getLastPathComponent(); return ((File)
node
.getUserObject()).getAbsolutePath(); } private DefaultTreeModel createTreeModel() { File root = FileSystemView.getFileSystemView().getRoots()[0]; File
Node
root
Node
= new File
Node
(root); root
Node
.explore(); return new DefaultTreeModel(root
Node
); } public void dragEnter(DropTargetDragEvent dtde) { } public void dragOver(DropTargetDragEvent dtde) { Point pt = dtde.getLocation(); if (pt.equals(lastPoint)) { return; } if (ghostImage != null) { Graphics2D g2 = (Graphics2D) getGraphics(); // If a drag image is not supported by the platform, then draw my // own drag image if (!DragSource.isDragImageSupported()) { paintImmediately(ghostRect.getBounds()); // Rub out the last // ghost image and cue // line // And remember where we are about to draw the new ghost image ghostRect.setRect(pt.x - ptOffset.x, pt.y - ptOffset.y, ghostImage.getWidth(), ghostImage.getHeight()); g2.drawImage((ghostImage), AffineTransform .getTranslateInstance(ghostRect.getX(), ghostRect.getY()), null); } } TreePath path = getClosestPathForLocation(pt.x, pt.y); if (!(path == lastPath)) { lastPath = path; hoverTimer.restart(); } } public void dropActionChanged(DropTargetDragEvent dtde) { } public void drop(DropTargetDropEvent e) { try { DataFlavor stringFlavor = DataFlavor.stringFlavor; Transferable tr = e.getTransferable(); TreePath path = this.getPathForLocation(e.getLocation().x, e.getLocation().y); if (path == null) { e.rejectDrop(); return; } File
Node
node
= (File
Node
) path.getLastPathComponent(); if (e.isDataFlavorSupported(DataFlavor.javaFileListFlavor) &&
node
.isDirectory()) { e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); System.out.println("file cp"); List list = (List) (e.getTransferable() .getTransferData(DataFlavor.javaFileListFlavor)); Iterator iterator = list.iterator(); File parent =
node
.getFile(); while (iterator.hasNext()) { File f = (File) iterator.next(); cp(f, new File(parent, f.getName())); }
node
.reexplore(); e.dropComplete(true); this.updateUI(); } else if (e.isDataFlavorSupported(stringFlavor) &&
node
.isDirectory()) { String filename = (String) tr.getTransferData(stringFlavor); if (filename.endsWith(".txt") || filename.endsWith(".java") || filename.endsWith(".jsp") || filename.endsWith(".html") || filename.endsWith(".htm")) { e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); File f = new File(filename); if (f.exists()) { f.renameTo(new File(
node
.getFile(), f.getName()));
node
.reexplore(); ((File
Node
) source
Node
.getParent()).remove(source
Node
); e.dropComplete(true); this.updateUI(); } else { e.rejectDrop(); } } else { e.rejectDrop(); } } else { e.rejectDrop(); } } catch (IOException ioe) { ioe.printStackTrace(); } catch (UnsupportedFlavorException ufe) { ufe.printStackTrace(); } finally { ghostImage = null; this.repaint(); } } private void cp(File src, File dest) throws IOException { if (src.isDirectory()) { if (!dest.exists()) { boolean ret = dest.mkdir(); if (ret == false) return; } File[] fs = src.listFiles(); for (int i = 0; i < fs.length; i++) { cp(fs[i], new File(dest, fs[i].getName())); } return; } byte[] buf = new byte[1024]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); int len; try { while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } finally { in.close(); out.close(); } } public void dragExit(DropTargetEvent dte) { } } class File
Node
extends DefaultMutableTree
Node
{ private boolean explored = false; public File
Node
(File file) { setUserObject(file); } public boolean getAllowsChildren() { return isDirectory(); } public boolean isLeaf() { return !isDirectory(); } public File getFile() { return (File) getUserObject(); } public boolean isExplored() { return explored; } public boolean isDirectory() { File file = getFile(); return file.isDirectory(); } public String toString() { File file = (File) getUserObject(); String filename = file.toString(); int index = filename.lastIndexOf(File.separator); return (index != -1 && index != filename.length() - 1) ? filename .substring(index + 1) : filename; } public void explore() { if (!isDirectory()) return; if (!isExplored()) { File file = getFile(); File[] children = file.listFiles(); for (int i = 0; i < children.length; ++i) { if (children[i].isDirectory()) add(new File
Node
(children[i])); } for (int i = 0; i < children.length; ++i) { if (!children[i].isDirectory()) add(new File
Node
(children[i])); } explored = true; } } public void reexplore() { this.removeAllChildren(); explored = false; explore(); } }
java美化JScrollPanel的滚动条
主要代码: setTitle("滚动美化"); setSize(800, 600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container container = getContentPane(); container.setLayout(null); DefaultMutableTree
Node
root = new DefaultMutableTree
Node
(); DefaultTreeModel model = new DefaultTreeModel(root); for (int i = 0; i < 200; i++) { root.add(new DefaultMutableTree
Node
("
node
_
node
_
node
_
node
_
node
_" + i)); }
JTree
jTree
= new
JTree
(model); JScrollPane jScrollPane = new JScrollPane(
jTree
); jScrollPane.setBounds(10, 10, 200, 200); jScrollPane.getVerticalScrollBar().setUI(new ScrollBarUIEx (JScrollBar.VERTICAL)); jScrollPane.getHorizontalScrollBar().setUI(new ScrollBarUIEx (JScrollBar.HORIZONTAL)); container.add(jScrollPane); setVisible(true);
java界面程序代码
fdspackage mypkg; import java.awt.*; import java.awt.event.*; import javax.
swing
.*; import javax.
swing
.event.*; import java.util.*; import java.sql.*; import java.sql.Statement; import javax.
swing
.table.*; import javax.
swing
.tree.*; /** * * @author Administrator */ public class ClassBrowse extends JFrame implements TreeSelectionListener { Statement stmt; ResultSet rs,rsl; DefaultTableModel dtm;//定义数据模型 String[]title;//表头数组
JTree
tree;//树 JTable table; DefaultTreeModel treeModel = null;//定义一个默认的树模型,用于建立树 JScrollPane scroll1,scroll2;//定义两个滚动面板 JSplitPane splitPane;//定义一个分割面板 private Object con; public ClassBrowse(){ try{ stmt = ConnectServer1. con. createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); DefaultMutableTree
Node
root = new DefaultMutableTree
Node
("专业");//根 treeModel = new DefaultTreeModel(root);//建立树模型 initTree(root,0);//调用递归函数建立树模型 tree = new
JTree
(treeModel);//利用树模型建立树 scroll1 = new JScrollPane(tree); tree.addTreeSelectionListener(this); rs = stmt.executeQuery("select classclass.name as 班级,xsda.no as 学号,xsda.name as 姓名" + " from xsda,classclass where xsda.classid = classclass.id"); ResultSetMetaData dbmd = rs.getMetaData();//得到记录集的元数据,建立表头数组 title = new String[dbmd.getColumnCount()]; for(int i=1;i <=dbmd.getColumnCount();i++) title[i-1] = dbmd.getColumnName(i); dtm = new DefaultTableModel(null,title);//建立表格数据模型 table = new JTable(dtm);//利用数据模型建立表格 scroll2 =new JScrollPane(table); initTable();//建立表 splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,scroll1,scroll2); splitPane.setOneTouchExpandable(true); splitPane.setDividerLocation(200); this.getContentPane().add(splitPane,null);} catch(SQLException e){System.out.println(e);} setTitle("分类查询学生信息"); setSize(500,400); setVisible(true); } void initTree(DefaultMutableTree
Node
root,int id){//这是递归函数 DefaultMutableTree
Node
node
= null;//定义节点 try{ Statement stmt = ConnectServer1. con. createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery("select * from classclass where parent =" + id);//查询班级类表 while(rs.next()){ int nno = rs.getInt("id");//取得分类ID String nname = rs.getString("name").trim();//取得分类名称
node
= new DefaultMutableTree
Node
(nname);//建立树的节点 treeModel.insert
Node
Into(
node
, root, root.getChildCount());//插入节点 initTree(
node
,nno);} } catch(Exception e){} finally{ try{ rs.close(); }catch(Exception e){} } } public void valueChanged(TreeSelectionEvent e){
JTree
tree=(
JTree
)e.getSource(); //利用
JTree
的getLastSelectedPathCoponent()方法取得目前选取的节点 DefaultMutableTree
Node
selection
Node
= (DefaultMutableTree
Node
)tree.getLastSelectedPathComponent(); String name = ((String)selection
Node
.getUserObject()); String sql = "selcet classclass.name as 班级,xsda.no as 学号,xsda.name as 姓名 from xsda,classclass where xsda.classid = classclass.id"; if(!name.equals("专业")) sql=sql + "and classid in(select id from classclass where rtrim(ltrim(str(id)))like(select ltrim(rtrim(str(id)))+'%'from classclass where rtrim(ltrim(name))='"+name+"'))"; try{ rs = stmt.executeQuery(sql);//利用嵌套查询查出所有数据 initTable(); } catch(Exception ee){} } void initTable(){ dtm.setRowCount(0); try{ rs.beforeFirst(); while(rs.next()){ Vector v1=new Vector(); for(int i=1;i <=title.length;i++) v1.addElement(rs.getString(i)); dtm.addRow(v1); } }catch(SQLException e){e.printStackTrace();} dtm.fireTableStructureChanged(); } public static void main(String arg[]){ JFrame.setDefaultLookAndFeelDecorated(true); Font font = new Font("JFrame",Font.PLAIN,14); Enumeration keys = UIManager.getLookAndFeelDefaults().keys(); while(keys.hasMoreElements()){ Object key = keys.nextElement(); if(UIManager.get(key)instanceof Font) UIManager.put(key, font); } if(!ConnectServer1.conn("jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=xsgl","sa","")){ JOptionPane.showMessageDialog(null, "连接数据库失败"); System.exit(0);//关闭数据库 } new ClassBrowse(); } }
Java SE
62,614
社区成员
307,327
社区内容
发帖
与我相关
我的任务
Java SE
Java 2 Standard Edition
复制链接
扫一扫
分享
社区描述
Java 2 Standard Edition
社区管理员
加入社区
获取链接或二维码
近7日
近30日
至今
加载中
查看更多榜单
社区公告
暂无公告
试试用AI创作助手写篇文章吧
+ 用AI写文章