i have a problem implementing ActionListener on a group of 10 jButtons. Each button has its text property set to a digit, from 0 – 9. So jButton1 will have its text property set to 1, JButton2 will have 2 as its text, …., …. then jButton9 will have its text set to 9. When i click any of those buttons, i want to append the value of its text property to a JTextField.
The problem am getting is every time i click a button, the value of its text property is printed twice, some times thrice some even four times, it just happens randomly.
For example, if i click a button with text 4 once, i can get 44 printed in the JTextField, if i then click 7 only once again, i can end up with 4477 or even 447777. below is my code
public class tCalculator extends JFrame implements ActionListener{
public tCalculator(){
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
btn4.addActionListener(this);
btn5.addActionListener(this);
btn6.addActionListener(this);
btn7.addActionListener(this);
btn8.addActionListener(this);
btn9.addActionListener(this);
btnZero.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
String x = txtArea.getText();
String k = evt.getActionCommand();
String a = x + k ;
txtArea.setText(a);
}}
private void btn1ActionPerformed(java.awt.event.ActionEvent evt) {
ActionListener actionListener = new tCalculator();
btn1.addActionListener(actionListener);
}
Your method
btn1ActionPerformedadds anotherActionListener. We do not see where it is called, but this would explain your problem. Whenever you click the button, you have one moreListenerwhich is executed at the next click.Looks like this code was generated by an IDE. Remove that action there and your code should work.
EDIT:
tCalculatorand put the code into the constructor ofJFrame1(belowinitComponents.These steps ensure that your Listener is registered exactly once per button.
BTW:
tCalculatorto extendJFrame. Remove that.TCalculator). A better name could beButtonActionListeneror something like that.