ActionListener, ActionPerformed

Hey,

I’m struggling performing an action with the variable jButton1, 2, and 3, outputing a string value if button clicked in the jTextArea1.

(Yes, no imports because the GUI has been designed in NetBeans).


public class RockPaperScissors extends javax.swing.JFrame {

    public RockPaperScissors() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton1   = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jTextArea1.setEditable(false);
        jScrollPane1.setViewportView(jTextArea1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(66, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Rps().setVisible(true);
            }
        });
    }

    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JButton jButton1;

}


Huh? What are you trying to do? Print text from a button that is clicked into the jTextArea1? Or something else?

So here is the deal. For an action to be performed on, there has to be a listener.

ActionListener is an interface and if something wants to respond to ActionPerformed events that object must implement that interface.
http://download.oracle.com/javase/6/docs/api/java/awt/event/ActionListener.html

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

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MainClass extends JPanel {

  public MainClass() {

    JButton btn1 = new JButton("Button1");
    btn1.addActionListener(new ButtonListener());
    add(btn1);

  }

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

class ButtonListener implements ActionListener {
  ButtonListener() {
  }

  public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals("Button1")) {
      System.out.println("Button1 has been clicked");
    }
  }
}

Though it’s also with a system output message, which I don’t need, I need to set a certain text for jtextarea. :slight_smile:

For sure.

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!");
    }
  }
}