Aaronward Aaronward - 7 months ago 12
Java Question

How to add an anonymous instance off a class as an ActionListener

Im working on a lab that requires me to make a JFrame with 2 inner classes. One that entends JPanel, has a text area and a jbutton. And another that implements action listener. How do i add an anonymouse instance of the second class to my JButton that is already in an inner class. Here is the brief to get a better understanding.

enter image description here

here is the code i have written so far. I can get the Frame to appear, but the JPanel doesnt appear, nor does the JButtons or JTextArea.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;



@SuppressWarnings("serial")
public class FormFrame extends JFrame
{

public static void main(String[] args)
{
JFrame frame = new FormFrame();
frame.setLocationRelativeTo(null);
}
public FormFrame()
{
Container contentPane = getContentPane();

RegisterPanel p = new RegisterPanel();
p.button.addActionListener(new SubmitResponder());
//
// Here is where im lost...
//


contentPane.add(p);
setSize(300, 200);
setVisible(true);
}

class RegisterPanel extends JPanel
{

JPanel panel = new JPanel();
JTextField text = new JTextField();
JButton button = new JButton("Submit");
}

class SubmitResponder implements ActionListener
{

@Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== RegisterPanel.button) //Asks me to make button static here
{

//Shows "No enclosing instance of the type FormFrame.RegisterPanel is accessible in scope"
RegisterPanel.this.text.setText("Submit Complete");

}
}
}
}


Any help with this would be much appreciated

Answer

You could pass the RegisterPanel instance to the action listener:

class SubmitResponder implements ActionListener {

    private final RegisterPanel rp;

    public SubmitResponder(RegisterPanel rp) {
        this.rp = rp;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        rp.text.setText("Submit Complete");
    }
}

There's no need to check the source btw. The AL is only listening to 1 source.

RegisterPanel p = new RegisterPanel();
p.button.addActionListener(new SubmitResponder(p));