JFrame ActionListener
JFrame myframe = new JFrame("My Sample Frame");
JButton mybutton = new JButton("Okay");
Can someone explain to me these part.
mybutton.addActionL开发者_JAVA百科istener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
//Assuming that the content here will do something.
}
What exactly do you not understand about the code?
The code adds an action listener to the button. The actionPerformed
method of the action listener will be called when the button is clicked.
Note that an anonymous inner class is used here.
Anonymous Inner Class is used here.
You have technically implemented ActionListener. When you called addActionListener:
mybutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
//Assuming that the content here will do something.
}
You created an instance of an anonymous class, or a class that implements ActionListener without a name.
For the same please visit this link .
You should read this Tutorial about writing Event Listeners.
In order to have a button react to events (such as a click) it must have an ActionListener
.
In the code you posted, you are creating an anonymous class implementing ActionListener
public void mySetupFunction(){
mybutton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
//Do something when the button is clicked
});
}
is the same as doing :
public void mySetupFunction(){
mybutton.addActionListener(new MyEventHandler());
}
with :
public class MyEventHandler implements ActionListener{
public void actionPerformed(ActionEvent evt){
//Do something when the button is clicked
}
}
If it is safe to assume, you are either new to Event handling or new to Java either way I have generalised the answer to accomodate both cases :)
Expert Answer:ActionListener
There isn't one, it's really self led and reading the APIs
Simple Answer:A sugar coated explanation of what You provided in your code.
mybutton
is a reference to the instanciated Object JButton
xxxxxx.addActionListener()
is a function call to a Field inherited from class javax.swing.AbstractButton
JButton inherits AbstractButton fields and therefore takes us to the next explanation
new ActionListener(){}
ActionListener is an interface, we don't need to go this high up at all.. all we need to know is it listens for input to source from a given object
public void actionPerformed(ActionEvent e)
again this is a function call, it is the tip to our "Objects pyramid" and not atypically - will contain the response to what you want the base of your object to do .. in this case mybutton.
What you do from here is dependent on what you want actionPerformed() to do.
The question to ask yourself if this is part of an assignment is - What does this do? How does it Do it?
精彩评论