-2

I have, for example, 2 text fields (txt1 and txt2) and two buttons (btn1 and btn2). I want to build a single method that will set "hello" in txt1 if btn1 is pressed, or "hello" in txt2 if btn2 is pressed.

I thought about doing something like this:

txt1.setName("1"); txt2.setName("2");

in btn1 listener: setHello(txt1);
in btn2 listener: setHello(txt2);

setHello(String name){
(componentByName?(name)).setText("hello")
}

Is there a componentByName(name) method?

syb0rg
  • 8,057
  • 9
  • 41
  • 81
Mark
  • 1,540
  • 2
  • 13
  • 21
  • By what name do you mean? The variable name? What if the object has no name, say it is held in an array or collection? What if two variables with different names refer to the very same component object? Which variable "name" is the one that matters? I think that you're giving way too much importance to variable "names" when what is really important are object ***references***. – Hovercraft Full Of Eels Apr 28 '13 at 18:17

1 Answers1

0

Use ActionListener. Action Listner is used for any time that a button or something of an object is going to be pressed (most commonly used for buttons). The actionPerformed method is included with the ActionListener class.

    public void actionPerformed(ActionEvent e) {
         if(e.getSource() == button1)
             txt1.setName("1");
         else 
             txt2.setName("2");
    }

Dont forget to implement ActionListener into your class, and add the actionListener onto your buttons in your program.

Hope this helps!

user2277872
  • 2,963
  • 1
  • 21
  • 22