Java – is it possible to trigger JButton events through method calls – rather than JButton clicks?
Can events be triggered through method calls? (and click)
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 any way to implement it?
In fact, I came up with this idea when I tried to solve the problem I faced I posted a separate question
(about the previously published question): as far as the server client is concerned, I want to achieve this goal:
>When the client clicks a button in the GUI. > The string 'a' sent to the server. > When the server receives the string 'a' from the client, it calls' methoda '; The method a call will affect the GUI on the server side The client and server GUIs are updated accordingly
thank you.
Solution
JButton has a doclick () method inherited from abstractbutton
http://docs.oracle.com/javase/6/docs/api/javax/swing/AbstractButton.html#doClick
This means you can simply write
game.leftButton.doClick();