java - adding users to JList in chatroom GUI -
i'm trying write simple chatroom gui using java, including jlist show online users. first user chooses display name name displayed in jlist. here code:
(the problem inside createserver()
method sends name argument handler constructor, in order display in jlist!)
public class gui{ private jframe frame; private jbutton btnsend, btnconnect; private jtextarea txtchat; private jtextfield fldtext, fldname; private jlist clientlist; private defaultlistmodel listmodel; private jscrollpane sc, scclients; private jpanel jps2all, jps2client, jps2text; private string name; class handler implements actionlistener, mouselistener{ private string name = null; void handler(string name) { this.name = name; } @override public void actionperformed(actionevent e) { chatroom(); } @override public void mouseclicked(mouseevent e) { fldname.settext(""); listmodel.addelement(name); } } public void creatserver() { frame = new jframe("login"); frame.setbounds(50, 50, 300, 200); btnconnect = new jbutton("connect"); frame.add(btnconnect, borderlayout.east); fldname = new jtextfield("enter name"); fldname.addmouselistener(new handler()); name = fldname.gettext(); btnconnect.addactionlistener(new handler(name)); frame.add(fldname, borderlayout.center); frame.setvisible(true); } public void chatroom() { frame = new jframe("online friends"); frame.setbounds(100, 100, 400, 400); jps2all = new jpanel(); txtchat = new jtextarea(); txtchat.setrows(25); txtchat.setcolumns(25); txtchat.seteditable(false); sc = new jscrollpane(txtchat); jps2all.add(sc); frame.add(jps2all, borderlayout.west); //////////////////////// jps2text = new jpanel(); fldtext = new jtextfield(); fldtext.setcolumns(34); fldtext.sethorizontalalignment(jtextfield.right); jps2text.add(fldtext); frame.add(jps2text, borderlayout.south); ///////// jps2client = new jpanel(); listmodel = new defaultlistmodel(); clientlist = new jlist(listmodel); clientlist.setfixedcellheight(14); clientlist.setfixedcellwidth(100); scclients = new jscrollpane(clientlist); frame.add(jps2client.add(scclients), borderlayout.east); ///////// frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setvisible(true); frame.pack(); } }
and in main method:
public class chat { public static void main(string[] args) { gui gui = new gui(); gui.creatserver(); } }
this:
void handler(string name) { ...
should be
handler(string name) { ...
to constructor, instead of method. also, create handler
2 different parameter lists: empty, , string. need constructor both.
by way, code a lot easier follow if used usual java naming conventions. inverted in couple of places. also, mouselistener
has more methods need implemented - consider extending mouseadapter. finally, should create , access swing components in event dispatch thread.
Comments
Post a Comment