简体   繁体   中英

How do I call methods when actionPerformed is called in GUI

Here is my ButtonListener class in my GUI. I have several buttons within it, that when clicked, I want to call a certain method for each one, for instance:

public class ButtonListener implements ActionListener{
        public void actionPerformed( ActionEvent event ){
            if (event.getSource( ) == buttonA)

If button A is selected, I want to call a method and have its return statement displayed.

(If I understand you correctly)

You could have

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == buttonA)
    {
        ButtonAImpl x = new ButtonAImpl();
        x.myMethod();
    }
    if (e.getSource() == buttonB)
    {
        ButtonBImpl y = new ButtonBImpl();
        y.myMethod();
    }
 }

You may want to look at some design patterns to help in this scenaro...

MVC - http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

MVP - http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter

If I understand it, you should do the following (just an example):

class X{

  JButton firstButton;
  JButton secondButton;

  public X(){

   firstButton=new JButton("first");firstButton.setActionCommand("FB");
   secondButton=new JButton("second");secondButton.setActionCommand("SB");

  }//constructor closing

  public void method1(){}
  public void method2(){}

  class EventHandler extends ActionListener{

     public void ActionPerformed(ActionEvent e){

      String action=e.getActionCommand();

     if(action.equals("FB"))method1();
     else if(action.equals("SB"))method2();

    }//



  }//inner-class closing

}//calss closing

I think it's good practise to use a switch in this case because you've said you have several buttons.

public void actionPerformed(ActionEvent e) {
   switch (e.getSource())
    case buttonA:
         buttonACode();
         break;
    case buttonB:
         buttonBCode();
         break;
    default:
         someDefaultAction();
         break;
 }

If you would like to display the returned result you can replace buttonACode(); with System.out.println(buttonACode());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM