Implementing an inner anonymous action listener - java

I've been trying to implement this action listener as stated above but keep receiving two errors:
-Cannot instantiate the type ActionListener
-void is an invalid type for the variable incrementAction
I've been looking up similar examples but they all seem to point to the same method of implementing it.
This is where I've got to.
increment.addActionListener(new ActionListener());{
public void incrementAction(ActionEvent e){
this.incrementCount();
this.setTextField();
}
}

The signature of the ActionListener method is:
public void actionPerformed(ActionEvent e)
JButton increment = new JButton();
increment.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("ActionEvent received! ");
}
});

Related

Button actionlistener calls another action listener in the same class

I have a submit button (and an action listener) which checks if the number inserted into a Futoshiki puzzle is legal (checking a 2D array for duplications etc)
In another method I have the actual grid with an action listener that gets the numbers and inserts them into the 2D array.
JButton acction listener
JButton isRight = new JButton("Check My Answer");
isRight.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (!(puzzle.isLegal())) {
JOptionPane.showMessageDialog(FutoshikiFrame.this,
puzzle.getProblems(),
"You made a mistake!",
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(FutoshikiFrame.this,
"YOU WIN!",
"YES THATS FINE",
JOptionPane.INFORMATION_MESSAGE);
}
puzzle.printProblems.clear();
}
});
Grid action listener
public void keyReleased(KeyEvent e) {
String getInsertedValue = Emptysquare.getText();
int getInsertedIntValue = Integer.parseInt(getInsertedValue);
setSquareValue(r, c, getInsertedIntValue);
System.out.print(getSquareValue(r, c));
}
Is there a way I can access the keyReleased action listener from the JButton so it basically "submits" the contents of the grid and then checks if its legal?
Sure, just either keep a reference to that action listener and call the keyReleased method with a null value, or refactor out the content of keyReleased to an own method and call this method from both listeners.
Although 2 other methods were given, here is an additional way you could go about it, but I'm not sure which would be best to use.
public class YourClass {
JButton isRight;
public YourClass() {
this.isRight = new JButton();
this.isRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
YourClass.this.isRight.getKeyListeners()[0].keyReleased(null);
//Other action related code
}
});
isRight.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent e) {
//Key related code
}
//Other required key listener methods
});
}
}

Unable to create an anonymous object

I tried doing this:
ActionListener listener = new ActionListener( {
public void actionPerformed(ActionEvent e) {
}
});
And it gives me a compilation error called syntax error on token "(" and ")".
Can you please tell me where I'm going wrong. I want to create an anonymous object of the class implementing interface ActionListener.
You're using the content of the anonymous class as parameter to the constructor of ActionListener. Close the parenthesis first, then add the body of the anonymous class:
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
};
You need to move your parenthesis
↓<<<<<<<+
ActionListener listener = new ActionListener( { |
public void actionPerformed(ActionEvent e) { |
|
} |
}); |
^>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>+
In other words you need first to invoke constructor new ActionListener() and then add body of anonymous class {...}
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
};
You can't pass code block as argument new ActionListener( {...} )

What is this keyword referring to?

I thought I had a decent grasp on the this keyword. Something has me confused a little bit.
I have a method that adds an ActionListener to my button. This is what the method looks like
public void checkButtonState(){
button1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
}
});
}
I also have a constructor method in my class.. which looks like this
public CanvasA(){
try{
CanvasABackground = ImageIO.read(new File("C:\\Users\\user\\workspace\\Interface\\src\\01120156745.jpg"));
}catch(IOException ex){
}
setSize(450,490);
setLayout(null);
JLabel picLabel = new JLabel(new ImageIcon(CanvasABackground));
add(picLabel);
createEnterButton();
createCloseButton();
checkButtonState();
checkButtonState2();
}
When using the this keyword in the constructor, I get many different methods that popup. For example typing this. will generate many methods just called add and many many others. However, typing this. inside the
#Override
public void actionPerformed(ActionEvent arg0) {
}
method, genereates completely different methods.. basically the this keyword is referring to something else. In the first case, it's talking about my CanvasA class (which extends JPanel btw). Im curious what this is referencng when typed inside the actionPerformed method.
Thanks for your help.
Where
new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
//here this referes to ActionListener
}
});
is an new Annaymous inner class ,inside that this referes to the current instance of ActionListener
this here is referring to your action listener instance.

Class of Event handlers

is it possible in java to have a class where it has EventHandlers for with different functions? for example button1 will log you in, while button2 will log you out, is this possible? Here's the code I made it seems to be not working.
package event.handlers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TheHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent logInEvent) {
System.out.println("Button Login");
}
public void actionPerformed(ActionEvent cancelEvent) {
System.out.println("Cancel Login");
}
}
You either need two implementations of ActionListener, one for each button or the actionPerformed needs to determine the button by the event argument and take the appropriate action. Your code will not compile because the signatures for both methods are the same.
No. You can not have a class implement two methods with the same function signature. How would the compiler know which one to call for different events? The name you give to the arguments has no meaning to the compiler.
As an alternative, you can create multiple anonymous action listeners that simply forward the call to a method that does have a unique name if you want everything to be in the same class.
public class TheHandler {
public TheHandler() {
JButton login, cancel;
//initialize code here
login.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent logInEvent) {
loginPerformed(logInEvent);
}
});
cancel.addActionListener( new ActionListener() {
#Override
public void actionPerformed(ActionEvent cancelEvent) {
cancelPerformed(cancelEvent);
}
});
}
public void loginPerformed(ActionEvent logInEvent) {
System.out.println("Button Login");
}
public void cancelPerformed(ActionEvent cancelEvent) {
System.out.println("Cancel Login");
}
}
You may use getSource() or getActionCommand() method of ActionEvent.
#Override
public void actionPerformed(ActionEvent logInEvent) {
Object src=logInEvent.getSource();
String cmd=logInEvent.getActionCommand(); //It will return caption of button
if(src==btn1)
{
//
}
//Or
if(cmd.equals("Button1")) { ... }
}
You can not have multiple actionPerformed method in one class. Simple way is to do operation based on source of action like:
(in actionPerformed method)
if(e.getSource() == loginButtton) { // based on button variable if they are in same class and accessible in actionPerformed method
loginMethod()
} else if(e.getSource == logoutButton) {
logoutMethod()
}
or
if(e.getActionCommand().equals("loginButtton")) { // based on caption/text on button
loginMethod()
} else if(e.getActionCommand().equals("logoutButtton")) {
logoutMethod()
}
or you can have different anonymous class for different buttons like
loginButton.addActionListner(new ActionListerner(){
public void actionPerformed(ActionEvent loginEvent) {
loginMethod();
}
});
logoutButton.addActionListner(new ActionListerner(){
public void actionPerformed(ActionEvent cancelEvent) {
logoutMethod();
}
});
The problem there is that your two method signatures are identical. When Java tries to figure out which method to call, it can't tell the difference between the two.
I can think of two ways to do what you want:
Presumably, you are registering the listeners on the buttons like cancelButton.addActionListener(...). So you can either provide each button with its own anonymous inner class:
loginButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent logInEvent) {
System.out.println("Button Login");
}
}
cancelButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent cancelEvent) {
System.out.println("Cancel Login");
}
}
or you can define a single actionPerformed method that checks the source of the call:
public class TheHandler implements ActionListener {
JButton loginButton;
JButton cancelButton;
public TheHandler()
{
...
// Now, technically, this is bad form because you're leaking 'this'.
// But as long as this will only be called after this constructor finishes
// initializing, it's safe.
loginButton.addActionListener(this);
cancelButton.addActionListener(this);
...
}
...
#Override
public void actionPerformed(ActionEvent evt) {
if(evt.getSource() == loginButton)
System.out.println("Button Login");
else if(evt.getSource() == cancelButton)
System.out.println("Cancel Login");
}
}
Using anonymous inner classes can sometimes be clearer, because you see the code right next to the addListener call, but it also adds a lot of boilerplate, and if you're working on a very large progect that can take a while to load, reducing the number of classes can sometimes make it load a little faster (each anonymous inner class is another thing for the JVM to load).

Constructors in Inner classes (implementing Interfaces)

How would I go about writing a constructor for an inner class which is implementing an interface? I know I could make a whole new class, but I figure there's got to be a way to do something along the line of this:
JButton b = new JButton(new AbstractAction() {
public AbstractAction() {
super("This is a button");
}
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
});
When I enter this it doesn't recognize the AbstractAction method as a constructor (compiler asks for return type). Does anyone have an idea?
Just insert the parameters after the name of the extended class:
JButton b = new JButton(new AbstractAction("This is a button") {
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
});
Also, you can use an initialization block:
JButton b = new JButton(new AbstractAction() {
{
// Write initialization code here (as if it is inside a no-arg constructor)
setLabel("This is a button")
}
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
});
If you really need a contructor for whatever reason, then you can use an initialization block:
JButton b = new JButton(new AbstractAction() {
{
// Do whatever initialisation you want here.
}
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
});
But you can't call a super-class constructor from there. As Itay said though, you can just pass the argument you want into the call to new.
Personally though, I would create a new inner class for this:
private class MyAction extends AbstractAction {
public MyAction() {
super("This is a button.");
}
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
}
then:
JButton b = new JButton(new MyAction());
The resulting class is not of type AbstractAction but of some (unnamed, anonymous) type that extends/implements AbstractAction. Therefore a constructor for this anonymous class would need to have this 'unknown' name, but not AbstractAction.
It's like normal extension/implementation: if you define a class House extends Building and construct a House you name the constructor House and not Building (or AbstractAction just to com back to the original question).
The reason the compiler is complaining is because you are trying to declare a constructor inside your anonymous class, which is not allowed for anonymous classes to have. Like others have said, you can either solve this by using an instance initializer or by converting it to a non-anonymous class, so you can write a constructor for it.

Categories