0

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);
}
vels4j
  • 11,208
  • 5
  • 38
  • 63
Shell Scott
  • 1,679
  • 18
  • 28

3 Answers3

0

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

Sandiip Patil
  • 456
  • 1
  • 4
  • 21
  • no, "==" works, for example functionality of button "C" (Clean) work correctly with next code if (e.getSource()==clean){ field.setText(null);} wen I tap on "C" button all text is deleted from JTextfield!! but I can input any text only from keyboard – Shell Scott Jul 15 '13 at 08:35
  • @redavlr You should only ever compare strings for equality using `equals()`, not `==`, because `==` will only work with string literals known at compile time. – Theodoros Chatzigiannakis Jul 15 '13 at 08:37
  • clean is your button's caption?? I am sure it is the object name. Fo C you are comparing object not string. e.getSource() gives action button. – Sandiip Patil Jul 15 '13 at 08:43
  • Yes, but but0 is also object name for button 0 ( ... Can somebody write part of code which create jtextfield, one button and alction listener method which help to display value of this button in textfield after tapping? (( need help) – Shell Scott Jul 15 '13 at 08:48
  • I have edited my answer. and if but0 is name of the object than you should not compare it as =="but0"; just do ==but0. – Sandiip Patil Jul 15 '13 at 08:51
0

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.,

   }
vels4j
  • 11,208
  • 5
  • 38
  • 63
0

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);
}
Community
  • 1
  • 1
afsantos
  • 5,178
  • 4
  • 30
  • 54