listeners
【程序编程相关:我,一个C++程序员,面试遇到常考问题总】【推荐阅读:管理寓言:驴子之死】
event listeners are functions you define that will be called when events happen. the jfc/swing core tells each component - like jbuttons and jmenus - when an event they would be interested in occurs. this is how jbuttons know to make themselves look "clicked". you can also ask a jbutton to tell you when it gets clicked by registering an event listener with it. if you were to write java code with emacs, there would be 3 steps involved in registering an event listener with a jbutton: 【扩展信息:如何为指定用户或计算机设置域策略】
listeners are how anything gets done in swing. clicking on stuff causes events. events are sort of like little messages that get sent around inside your program. if you want, you can watch all these messages and try to filter out the ones you want. that would be a colossal waste of time, on top of being really, really inefficient. there are better ways to do things. namely, event listeners.1 - define the listener:
there are different kinds of events, so there are different kinds of listeners. jbutton generates an actionevent when it is clicked, so we create a class that implements the actionlistener interface...class anactionlistener implements actionlistener{
public void actionperformed(actionevent actionevent){ system.out.println("i was selected."); } } 2 - create an instance of the listener ok, this is pretty simple...actionlistener actionlistener = new anactionlistener();
3 - register the listener with a component start out by pretending you already have a jbutton and you want that listener function we wrote in step 1 to get called when j. random user clicks on it. you do this by registering it with the jbutton. essentially you ask the jbutton to add it to the list of functions it calls when it decides to generates an actionevent, like so...jbutton button = new jbutton();
... // other code button.addactionlistener(actionlistener);visual age to the rescue!
... 下一页