k_k_grass
发贴: 29
积分: 0
|
于 2003-03-26 21:02
/*1.run the program,and double click the child01 node and rename it which takes with carriage return 2.click the save button to save it; 3.I wanna get back the previous information with click open button,even i try to get it back,but it won't response to the TreeSelectionEvent,that is also my concern here... thanks advance for any of your idea */ import java.util.*; import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.tree.*; import javax.swing.*; import javax.swing.event.*; class Tree1 extends JFrame implements Serializable{ JTree tree; Hashtable h; JPanel panel; JScrollPane scroll; JButton btnOpen,btnSave; JLabel lblStatus; int count=0;//child tree node counts; String[] s1={"child"+count}; static Tree1 treeApp; public Tree1(){ //initialize the tree which constructed with hashtable h=new Hashtable(); h.put("root",s1); tree=new JTree; tree.setEditable(true); panel=new JPanel(); scroll=new JScrollPane(tree); btnOpen=new JButton("open"); btnSave=new JButton("save"); lblStatus=new JLabel(); tree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent(); if (node == null) return; Object nodeInfo = node.getUserObject(); lblStatus.setForeground(Color.red); lblStatus.setText(nodeInfo.toString()+"Selected"); validate();//re-layout & repaint repaint(); }
}); btnOpen.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ scroll.remove(tree); ObjectInputStream is=null; try{ is=new ObjectInputStream(new FileInputStream(new File("os.txt"))); Hashtable hB=(Hashtable)is.readObject(); JTree treeB=(JTree)is.readObject(); scroll.add(tree; treeB.setRootVisible(true); is.close(); validate(); repaint(); JOptionPane.showConfirmDialog(null,"opened the previous' tree","open",JOptionPane.PLAIN_MESSAGE); } catch(Exception et){System.out.println("wrong opening object");} } }); btnSave.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent event){ ObjectOutputStream os=null; try{ os=new ObjectOutputStream(new FileOutputStream(new File("os.txt"))); os.writeObject; os.writeObject(tree); JOptionPane.showConfirmDialog(null,"saved this tree","save",JOptionPane.PLAIN_MESSAGE); } catch(Exception e){System.out.println("error write object");} finally{ try{ os.close(); } catch(Exception e){System.out.println("error on close");} } } }); setContentPane(panel); panel.setLayout(new BorderLayout()); panel.add(scroll,BorderLayout.WEST); JPanel btnPanel=new JPanel(); btnPanel.add(btnOpen); btnPanel.add(btnSave); panel.add(btnPanel,BorderLayout.NORTH); panel.add(lblStatus,BorderLayout.SOUTH); setSize(300,400); show(); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); }
public static void main(String[] args){ treeApp=new Tree1(); } }
|