Simple Chat Program tutorial (vi) main window and Chat window

Source: Internet
Author: User
Tags event listener

Source code Download Link: http://download.csdn.net/detail/sky453589103/9514686

If you have any questions, please leave a message.

The main window uses the JList control, after displaying the logged in with the person information, next is the friend's list.

In order to facilitate the future expansion, I put my friend's information encapsulated in the friendinformation, Friendinformation class definition is very simple, can read.


Let's step through the Mainwin class:

The more important thing in Mainwin is the monitoring of events:

Listen to the right-click menu in your buddy list:

JMenuItem item = new JMenuItem ("Remove"), Item.addactionlistener (new ActionListener () {@Overridepublic void actionperformed (ActionEvent arg0) {//TODO auto-generated method Stubrequestmessage request = new Requestmessage (); Request.setfrom (username), Request.setto (Friendjlist.getselectedvalue (). GetName ()); Request.setcommand ("Remove a Friend "); try {printstream out = new PrintStream (Getserver (). Getoutputstream ()); Out.print (Request. Format ());} catch (IOException e) {}}}); Friendlistpopupmenu.add (item);
Since there is only one option in my right-click menu, it is very simple to write, but it is sufficient for example. When this option is selected, the client will generate a delete request message sent to the server side, server-side hi to perform this action, if the deletion succeeds, the deleted friends list is returned.


The selected mode of the buddy list should be a single radio, set by the following function:

This.friendJList.setSelectionMode (listselectionmodel.single_selection);

Listen to your buddy list:

This.friendJList.addMouseListener (New MouseListener () {@Overridepublic void mouseclicked (MouseEvent e) {//if mouse ' s Right key click, the line would be Selected.if (E.getbutton () = = 3) {Friendjlist.setselectedindex (friendjlist.locationtoin Dex (E.getpoint ()));} Getbutton function ' s return value has three value.//1 represent Mouse's left key.//3 represent mouse ' s right key.if ( E.getbutton () = = 1 && e.getclickcount () >= 2) {//index of being double clicked line//int index = friendjlist. Getselectedindex (); Friendinformation f = (friendinformation) friendjlist.getselectedvalue ();//Friendinformation F = friendList.get (index if (F.getstatus (). Equals ("on")) {Addchatwin (F.getname ());} else {joptionpane.showmessagedialog (null, f.getname () + "Is offline!", "message", Joptionpane.information_message);} Friendjlist.clearselection ();} else if (e.getbutton () = = 3 && friendjlist.getselectedindex () >= 0) {friendlistpopupmenu.show (e.getcomponent (), E.getx (), e.gety ());}});

Omitted three functions can not see, are empty.

if (E.getbutton () = = 3) {Friendjlist.setselectedindex (Friendjlist.locationtoindex (E.getpoint ()));}

The Getbutton function will have three return values, 1 for the left button, 2 for the Middle key, and 3 for the right key.

This code, the implementation is, if the right-click a row, this line will also be selected.

The next judgment

1. The left button double-clicked a row. If so, create a response Chat window and display it if the chat window exists.

2. If you right-clicked a row, the right-click menu pops up.

To customize the rendering mode of the jlist, you need to call the Setcellrenderer function before it takes effect:

Class Friendjlistrenderer extends JPanel implements listcellrenderer<friendinformation> {/** * */private static fi nal Long serialversionuid = 1l;private JLabel Lbicon = new JLabel ();p rivate JLabel lbname = new JLabel ();p rivate JLabel lb Status = new JLabel ();p ublic friendjlistrenderer () {setlayout (New BorderLayout (5, 5)); JPanel paneltext = new JPanel (new GridLayout (0, 1));p Aneltext.add (lbname);p aneltext.add (lbstatus); Add (Lbicon, Borderlayout.west); Add (Paneltext, borderlayout.center);} @Overridepublic Component getlistcellrenderercomponent (jlist<? extends friendinformation> list, Friendinformation Friend,int Index, Boolean isSelected, Boolean cellhasfocus) {ImageIcon icon = new ImageIcon (GetClass (). GetResource ("/simplechat/mushroom2.png")); Lbicon.seticon (icon);//Lbicon.settext ("This is a icon \ r \ n" Show by list\r\n//error? "); Lbname.settext (Friend.getname ()); Lbstatus.settext (Friend.getstatus ()); Lbstatus.setforeground (Color.blue);//Set Opaque to change background coloR of Jlabellbname.setopaque (TRUE); Lbstatus.setopaque (true); Lbicon.setopaque (true);//When Select ITEMIF (isSelected) {Lbname.setbackground (List.getselectionbackground ()); Lbstatus.setbackground (List.getselectionbackground ()); Lbicon.setbackground (List.getselectionbackground ()); SetBackground (List.getselectionbackground ());} else {//when don ' t Selectlbname.setbackground (List.getbackground ()); Lbstatus.setbackground (List.getbackground ()); Lbicon.setbackground (List.getbackground ()); SetBackground (List.getbackground ());} return this;}}


To add a friend's button to the event listener:

After you press the Add Friend button, a window with an input box appears, and after you enter the name of the friend you want to add, you can perform the action of adding a friend.

Addfriendbutton.addactionlistener (new ActionListener () {@Overridepublic void actionperformed (ActionEvent arg0) {// String Inputvalue = Joptionpane.showinputdialog (This, "please//input a name"); String inputvalue = Joptionpane.showinputdialog (null, "Please input a name", "Add a new friend", Joptionpane.closed_option if (!inputvalue.equals (")") {Requestmessage request = new Requestmessage (); Request.setfrom (username); Request.setto (Inputvalue); Request.setcommand ("Add a Friend"); try {printstream out = new PrintStream (Getserver (). Getoutputstream ()) ; Out.print (Request. Format ());} catch (IOException e) {}}});


It is important to note that after the login operation, all messages from the server's response are received in the STARTN function and are then processed according to the code and description of the response message. Because of the length of the reason, this is not unfolding.

In the Chat window, only the message text is added and sent, and the four-level operation to receive the information is done in the main window. Because in doing so you can avoid having multiple streams at the same time listening for input, which causes confusion.

When the Chat window receives the information of the other party, it adds the current system time, which is implemented by the following code:

public void AddMessage (string from, string content) {Date date = new Date (); Messagetextarea.settext ( Messagetextarea.gettext () + "\ r \ n" + from + "    + dateformat.format (date) +" \ r \ n "+ content);}
Gets the current system time by using the date class, and formats the message to be added to the Message text box.

Simple Chat Program tutorial (vi) main window and Chat window

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.