Constructors in Inner classes (implementing Interfaces) - java

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.

Related

Pass Method as parameter for another Method in Java

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);

Separate Class for multiple action listener

I want to find the best practice to separate actionListener to an individual class. Throughout my research , the only things that i found is to create one actionlistener for one class.java which did not solve my issue.
For an example ,
launch.java
public class launch {
public launchSystem(){
....
JButton click1 = new JButton("Click 1");
JButton click2 = new JButton("Click 2");
//--- Add actionListener
// click1.addActionListener(new clickAction_b);
frame.add(click1);
frame.add(click2);
}
}
listenerClass.java
public class listenerClas {
class clickAction_A implements ActionListener{
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("click a");
}
}
class clickAction_B implements ActionListener{
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("click b");
}
}
}
In this case , i want to add "clickAction_b to my cliaddActionListener" but unable to do so . I tried using extend and interface but all failed. Is it even possible to linked multiple actionlistener like calling a method from a different class?

Implementing an inner anonymous action 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! ");
}
});

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).

Categories