In QQ, we want to communicate with friends, select the group where the friends are located, and double-click the Friends option to bring up the chat dialog box. here we need to implement this step, I used the JTree component in the previous function of displaying the friend list. Therefore, a tree structure is displayed, which can be divided into root nodes, branch nodes, and leaf nodes, the node in the pop-up box is the leaf node. When we double-click the function, we need to make a judgment.
tree = new JTree (top);
tree.addMouseListener (new MouseAdapter () {
@Override
public void mouseClicked (MouseEvent e) {
if (e.getClickCount () == 2) {
DefaultMutableTreeNode note = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent ();
if (note.isRoot ()) {
System.out.println ("root" + note.toString ());
} else if (note.isLeaf ()) {
System.out.println ("leaf node" + note.toString ());
} else {
System.out.println ("branch node" + note.toString ());
}
}
super.mouseClicked (e); // To change body of generated methods, choose Tools | Templates.
}
});
I added a double-click mouse event to the JTree and checked the implementation effect of the above Code:
run:
root friend
root friend
Branch node customer
Leaf node
Leaf node
We can see from the above that the leaf node is what we want. When you double-click a branch node, we need to create a dialog box in which the JPanel design layout is used. When you double-click a friend, the chat dialog box is displayed. In the above Code, we add a dialog box function,
tree = new JTree (top);
tree.addMouseListener (new MouseAdapter () {
@Override
public void mouseClicked (MouseEvent e) {
if (e.getClickCount () == 2) {
DefaultMutableTreeNode note = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent ();
if (note.isRoot ()) {
System.out.println ("root" + note.toString ());
} else if (note.isLeaf ()) {
System.out.println ("leaf node" + note.toString ());
ChatPanel chatPanel = new ChatPanel ();
JDialog chatDialog = new JDialog ();
chatDialog.setContentPane (chatPanel);
chatDialog.setSize (501, 512);
chatDialog.setVisible (true);
} else {
System.out.println ("branch node" + note.toString ());
}
}
super.mouseClicked (e); // To change body of generated methods, choose Tools | Templates.
}
});
As follows:
Of course, the current effect is only a box. If we want to implement communication, we need to rewrite this JDialog and pass the required parameters to JDialog. We will put this in the following chapter.