日期:2014-05-20 浏览次数:20774 次
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.tree.*; public class JTreeFrame extends JFrame { private JTree tree; private DefaultTreeModel model; private DefaultMutableTreeNode root = new DefaultMutableTreeNode("root"); private DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("node1"); private DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("node2"); private DefaultMutableTreeNode node3 = new DefaultMutableTreeNode("node3"); public JTreeFrame() { //添加各结点 root.add(node1); root.add(node2); node1.add(node3); model = new DefaultTreeModel(root); tree = new JTree(model); //添加监听 tree.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent event) { if (event.getButton() == MouseEvent.BUTTON3) { JPopupMenu popupMenu = new JPopupMenu(); JMenuItem itemShow = new JMenuItem("弹出窗口按钮"); popupMenu.add(itemShow); popupMenu.show(JTreeFrame.this, event.getX(), event.getY()); } } }); //添加JTree add(new JScrollPane(tree)); } public static void main(String[] args) { JFrame frame = new JTreeFrame(); frame.setSize(400, 300); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }