Reputation: 25
I have the simple following code:
button.addActionListener(new ComeOnListener(jTextArea1));
button.addActionListener(new ComeOnListener(jTextArea2));
ComeOnListener is implemented as a private class (it was somehow syntactically confusing trying to implement it as anonymous) and it appends "Come on!" on the text area it receives as parameter. Nevertheless, it is only appending it on jTextArea2, completely ignoring jTextArea1. The listener goes as follow:
private class ComeOnListener implements ActionListener {
JTextArea auxTextArea;
public ComeOnListener(JTextArea jta) {
auxTextArea = jta;
}
@Override
public void actionPerformed(ActionEvent e) {
auxTextArea.append("¡Come on!");
//throw new UnsupportedOperationException("Not supported yet.");
}
}
Could someone please tell me what's going on?
Thank you very much.
Upvotes: 1
Views: 2421
Reputation: 36611
As always, you should post an SSCCE . Here is a working piece of code showing the wanted functionality
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AppendTextArea {
public static void main( String[] args ) {
EventQueue.invokeLater( new Runnable() {
@Override
public void run() {
JFrame frame = createUI();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.pack();
frame.setVisible( true );
}
} );
}
private static JFrame createUI(){
JFrame result = new JFrame( "TestFrame" );
JTextArea firstArea = new JTextArea( 30, 30 );
JTextArea secondArea = new JTextArea( 30,30 );
JButton appendButton = new JButton( "Append" );
appendButton.addActionListener( new ComeOnListener( firstArea ) );
appendButton.addActionListener( new ComeOnListener( secondArea ) );
result.add( firstArea, BorderLayout.NORTH );
result.add( secondArea, BorderLayout.CENTER );
result.add( appendButton, BorderLayout.SOUTH );
return result;
}
private static class ComeOnListener implements ActionListener {
private final JTextArea auxTextArea;
public ComeOnListener(JTextArea jta) {
auxTextArea = jta;
}
@Override
public void actionPerformed(ActionEvent e) {
auxTextArea.append("Come on!");
}
}
}
As you can see, the code you posted is just copied into this snippet and works as expected. Most likely the problem is located elsewhere in your code.
Upvotes: 3