Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible: trigger JButton events via method call - not JButton clicks?

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.

like image 704
Saleh Feek Avatar asked Dec 06 '22 10:12

Saleh Feek


1 Answers

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();
like image 99
Qwerky Avatar answered Mar 23 '23 01:03

Qwerky