I know that I should use "actionlistener", so I suppose that the below code should work but it doesn't.
if (e.getSource() == "but0") { // but0 is name of button with number "0"
String aaa = but0.getText();
field.setText(aaa);
}
I know that I should use "actionlistener", so I suppose that the below code should work but it doesn't.
if (e.getSource() == "but0") { // but0 is name of button with number "0"
String aaa = but0.getText();
field.setText(aaa);
}
The button caption should be read using .equals(). == won't work here.
Try e.getSource().getText().equals("0")
Or compare the object directly as e.getSource()==but0
Add button in array when creating it
ArrayList<JButton> buttonA = new ArrayList();
for(int i=0;i<=9;i++) {
String num_ = String.valueOf(i);
JButton button = new JButton(num_);
button.setName(num_);
buttonA.add(button);
// do remaining stuff
}
In action
public void actionPerformed(ActionEvent e) {
if(buttonA.contains(e.getSource())) {
JButton btn = (JButton) e.getSource();
display.setText(display.getText() + btn.getName());
} else if() { // operations like +,- etc.,
}
From the JavaDocs, on java.awt.event.EventObject
:
public Object getSource()
The object on which the Event initially occurred.
Instead of comparing with a String, try comparing with the button itself:
if (e.getSource() == but0) {
String aaa = but0.getText();
field.setText(aaa);
}