swing - Popupmenu wont work in java? -
i constructing word processor program assignment java class in school , having hard time getting popupmenu work when right click on text area. have constructed popup menu , have textarea listening popuplistener , have overridden mouse pressed , mouse released functions
class popupframe extends jframe{ jmenuitem copy; jmenuitem paste; jtextarea textarea = new jtextarea(); jpopupmenu pop; popupframe(){ container cpane = getcontentpane(); setsize(300 , 300); setlocation(300, 300); settitle("test"); jpopupmenu pop = new jpopupmenu(); copy = new jmenuitem("copy"); paste = new jmenuitem("paste"); textarea = new jtextarea("something goes here", 5, 5); pop.add(copy); pop.add(paste); popuplistener popuplistener = new popuplistener(); textarea.addmouselistener(popuplistener); } class popuplistener extends mouseadapter{ public void mousepressed(mouseevent e){ popit(e); } public void mousereleased(mouseevent e){ popit(e); } private void popit(mouseevent e){ if(e.ispopuptrigger()){ pop.show(e.getcomponent(), e.getx(), e.gety()); } } } }
i cannot see why not working perhaps missing crucial, please help!! appreciated
add @override
annotation methods think overriding...
class popuplistener extends mouseadapter { @override public void mousepressed(mouseevent e) { system.out.println("pressed"); popit(e); } @override public void mousereleased(mouseevent e) { system.out.println("pressed"); popit(e); }
you find fails compile, why? because java case sensitive, , convention, method names start lower case character
you'll find like...
class popuplistener extends mouseadapter { @override public void mousepressed(mouseevent e) { popit(e); } @override public void mousereleased(mouseevent e) { popit(e); } @override public void mouseclicked(mouseevent e) { popit(e); } private void popit(mouseevent e) { if (e.ispopuptrigger()) { pop.show(e.getcomponent(), e.getx(), e.gety()); } } }
will work better. having said that, you'll find
textarea.setcomponentpopupmenu(pop);
significantly easier , less error prone (and won't cause nullpointerexception
example code will.
Comments
Post a Comment