4

Is it possible to trigger events by method call? (alongside with clicks). below is a sample code. it is not a working code, it just demonstrates how I imagine it.

import java.awt.event.*;
import javax.swing.*;

public class Game extends JFrame
{

    JButton leftButton = new JButton("left");
    JButton rightButton = new JButton ("right");

    private JButton Move(String moveClickString)
    {
        JButton chosenButton = new JButton();

        if (moveClickString.equals("left"))
        {
            chosenButton = leftButton;
        }
        if (moveClickString.equals("right"))
        {
            chosenButton = rightButton;
        }
        return chosenButton;
    }

    public void actionTrigger(JButton buttonClick)
    {
        buttonClick.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                Object buttonPressed = e.getSource();

                if (buttonPressed == leftButton);
                {
                    //do left
                }

                if (buttonPressed == rightButton);
                {
                    //do right
                }
            }
        });
    }

    public static void main(String[] args)
    {
        Game game = new Game();
        game.setVisible(true);

        game.actionTrigger(game.Move("left")); //some way to execute things?.
    }
}

Is there some way to execute things?.

Actually this idea comes to my mind when I was trying to solve a problem I am facing with. I posted a separate question about it.

(regarding that previous posted question): In terms of server-client I want to achieve this:

  • When the client clicks a button in the GUI.

  • A string 'A' sent to the server side.

  • When the server receives the string 'A' from the client it invoke 'methodA'; methodA invocation will
    affect the GUI in the server side. So that Client and Server GUIs updated correspondingly.

Thank you.

Community
  • 1
  • 1
Saleh Feek
  • 2,048
  • 8
  • 34
  • 56

1 Answers1

15

JButton has a doClick() method inherited from AbstractButton.

http://docs.oracle.com/javase/6/docs/api/javax/swing/AbstractButton.html#doClick

which means you can simply write

game.leftButton.doClick();
Qwerky
  • 18,217
  • 6
  • 44
  • 80