Path: csiph.com!usenet.pasdenom.info!gegeweb.org!aioe.org!.POSTED!not-for-mail From: Jail Bush Cronies Newsgroups: comp.lang.java.programmer Subject: Re: I need a different approach - suggestions please Date: Wed, 27 Jun 2012 18:46:59 -0400 Organization: Jail Bush Cronies Lines: 62 Message-ID: References: <1u-dnQTm2NDQGnbSnZ2dnUVZ_rydnZ2d@earthlink.com> NNTP-Posting-Host: Sb/6PuiVCS+2dP9QF7lKrw.user.speranza.aioe.org Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: abuse@aioe.org User-Agent: NewsTap/3.5.5 (iPhone/iPod Touch) X-Notice: Filtered by postfilter v. 0.8.2 Xref: csiph.com comp.lang.java.programmer:15685 On 27/06/2012 6:21 PM, Patricia Shanahan wrote: > On 6/27/2012 2:44 PM, bilsch wrote: > ... >> The listeners all call a statement in the second file: >> >> public void actionPerformed(ActionEvent event) >> >> so I don't understand how a button listener can be different from >> another button listener. > > You can write several different implementing classes for an interface > such as ActionListener. You can then create different instances of the > same implementing class. > > For example, you could have a NumberKeyListener class that implements > ActionListener, and takes a constructor parameter that tells it the > value associated with its button. On the other hand, I would have a > different class for dealing with backspace. > > Code like: > > one.addActionListener(new NumberKeyListener(1)); > two.addActionListener(new NumberKeyListener(2)); > > would get rid of a lot of checking which button was pressed. Another option uses the ActionEvent the listener gets passed, a parameter that's frequently ignored: public void actionPerformed (ActionEvent e) { JButton btn = (JButton)(e.getSource()); String btnTxt = btn.getText(); // btnTxt should be "0", "1", ..., or "9". // Do something with it. } Of course, this action listener will blow up if used on something other than a JButton. You also might not like the results if you later localize the button labels using a ResourceBundle or something. :) In the event that that sort of thing is likely, the numeric-parameter approach Patricia suggested is more robust. Another possibility is: private static Map buttonMap; ... for (int i = 0; i < 10; i++) { JButton btn = new JButton("" + i); btn.addActionListener(new NumberKeyListener()); buttonMap.add(btn,i); } ... public void actionPerformed (ActionEvent e) { int btnNum = buttonMap.get(e.getSource()); } Note: will throw NPE if attached to something other than a button that's in buttonMap. Also, for buttonMap to be visible in actionPerformed, NumberKeyListener needs to be a nested class of the class with the rest of this code.