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( {...} )
Related
I am creating a generic method to create action listeners for buttons, and i would like to be able to pass in another method into it's actionPerformed, rather than creating a new method for each use case of a listener. something like this:
public static ActionListener makeListener(Method method) {
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
method();
}
};
return listener;
}
Other similar posts have had recommended Lambda Expressions, but (maybe due to a lack of understanding), I don't think those are what i need. Are there other options?
Sounds like a Runnable is exactly what you need.
Declaration:
public static ActionListener make_listener(JButton button, Runnable action) {
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
action.run();
}
};
return listener;
}
Or using a lambda for the ActionListener (and skipping the local variable):
public static ActionListener make_listener(JButton button, Runnable action) {
return e -> action.run();
}
You can now call it with any zero-argument method using a lambda or method reference:
ActionListener listener1 = make_listener(() -> callMethod());
ActionListener listener2 = make_listener(this::callMethod);
I have:
class extended from JFrame;
an list of JTextField's elements - JTextField[] pix.
When clicking on pix[i] - JFrame must iconified and next click at any point of screen must changes exactly that textField (pix[i]) without any influence on another textFields, then frame must normalized and any mouseClicks after that (not on textField) couldn't influenced on that elements.
Clicks outside of JFrame processed with jnativehook library.
That part of code here:
for (int i = 0; i < pix.length; i++){
int tmp = i;
pix[i].addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
setState(Frame.ICONIFIED);
GlobalScreen.addNativeMouseListener(new NativeMouseAdapter(){
public void nativeMouseClicked(NativeMouseEvent e){
pixelChoose(pix[tmp]);
setState(Frame.NORMAL);
}
});
}
});
P.S.: I've tried to use
GlobalScreen.removeNativeMouseListener(new NativeMouseAdapter() {
public void nativeMouseClicked(NativeMouseEvent e) {
}
});
but don't actually know how to use this correctly.
P.S.[2]: if you have another solution of that question, you are welcome to type it into the answers - it will be great :>
EDIT!
I was buisy and now I'm here with solution:
NativeMouseAdapter adapter = new NativeMouseAdapter(){
public void nativeMouseClicked(NativeMouseEvent e){
pixelChoose(pix[tmp]);
setState(Frame.NORMAL);
GlobalScreen.removeNativeMouseListener(this);
}
};
MouseListener listener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
setState(Frame.ICONIFIED);
GlobalScreen.addNativeMouseListener(adapter);
}
};
pix[i].addMouseListener(listener);
Add (after the setState) code to remove the MouseListener.
setState(Frame.NORMAL);
for (int i = 0; i < pix.length; i++){
pix[i].removeMouseListener(MouseAdapter::this);
}
pix must be effectively final, and I hope MouseAdapter::this works for the anonymous MouseListener.
MouseAdapter::this fails
Instead of
pix[i].addMouseListener(new MouseAdapter() {
hold the MouseListener in its own variable:
MouseListener cat = new MouseAdapter() { ... };
pix[i].addMouseListener(cat);
And later do in the inner callback do
pix[i].removeMouseListener(cat);
In the code where you create the mouse listener, you need to keep a reference.
NativeMouseAdapter adapter = new NativeMouseAdapter(){
public void nativeMouseClicked(NativeMouseEvent e){
pixelChoose(pix[tmp]);
setState(Frame.NORMAL);
}
}
GlobalScreen.addNativeMouseListener(adapter);
Then when you want to remove it, you use that reference.
GlobalScreen.removeNativeMouseListener(adapter);
NativeMouseAdapter adapter = new NativeMouseAdapter(){
public void nativeMouseClicked(NativeMouseEvent e){
pixelChoose(pix[tmp]);
setState(Frame.NORMAL);
GlobalScreen.removeNativeMouseListener(this);
}
};
MouseListener listener = new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
setState(Frame.ICONIFIED);
GlobalScreen.addNativeMouseListener(adapter);
}
};
pix[i].addMouseListener(listener);
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! ");
}
});
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).
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.