是否可以通过方法调用触发事件? (以及点击).
下面是一个示例代码.它不是一个有效的代码,它只是演示了我的想象.
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?.
}
}
有办法执行吗?
实际上,当我试图解决我面临的问题时,我想到了这个想法.我发布了一个单独的question.
(关于之前发布的question):就服务器客户端而言,我想实现这个目标:
>当客户端单击GUI中的按钮时.
>发送到服务器端的字符串’A’.
>当服务器从客户端收到字符串’A’时,它调用’methodA’; methodA调用将
影响服务器端的GUI.这样客户端和服务器GUI就相应地更新了.
谢谢.