There are two preferred ways of handling ActionEvents. Having the container or the JPanel implement ActionListener and then added as a listener to each item that it contains and then perform an if statement to determine what behavior to actually do.
public class ExtendedJPanel extends JPanel implements ActionListener {
private JButton jButton1;
public ExtendedJPanel() {
jButton1 = new JButton("Press me");
jButton1.addActionListener(this);
}
public void ActionPerformed(ActionEvent actionEvent) {
if(actionEvent.getSource() == jButton1) {
JButton jbutton = (JButton)actionEvent.getSource();
System.out.println(jbutton.getText();
}
}
// Do some code here to display the JPanel.
}
Or, you could extend JButton to add the behavior of listening to itself and then have the button perform whatever behavior needs to be done itself. This is my preferred way of handling events.
public class ExtendedJButton extends JButton implements ActionListener {
// Override all constructors and just call the proper super constructor.
// BUT, each constructor must add the JButton to itself as a listener of itself...
public ExtendedJButton() {
addActionListener(this);
}
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Please Override the actionPerformed method anonymously");
}
}
public class ExtendedJFrame extends JFrame {
// Do code to setup your view and other components...
// Override the behavior of ExtendedJButton Anonymously...
ExtendedJButton jButton1 = new ExtendedJButton() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("actionPerformed overriden");
}
}
}
So where is the textarea that you need to set the text on?
You would have to pass the textarea to your ButtonListener some how. Either though a constructor or thought a setter method. This is where the beauty of one of the two ways I explained above comes into play.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainJPanel extends JPanel implements ActionListener {
private JButton btn1;
private JTextField txtfld1;
public MainJPanel() {
this.btn1 = new JButton("Button1");
this.btn1.addActionListener(this);
add(btn1);
this.txtfld1 = new JTextField();
add(txtfild1);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new MainClass());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(this.btn1)) {
this.txtfld1.setText("TextField updated!");
}
}
}