是否可以通过方法调用来触发事件? (连同点击)。 下面是一个示例代码。它不是一个工作代码,它只是展示了我的想象。
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”;方法调用将
影响服务器端的 GUI。以便客户端和服务器 GUI 相应更新。
谢谢。
最佳答案
JButton
有一个 doClick()
方法继承自 AbstractButton
。
http://docs.oracle.com/javase/6/docs/api/javax/swing/AbstractButton.html#doClick
这意味着你可以简单地写
game.leftButton.doClick();
关于java - 有没有可能 : trigger JButton events via method call - not JButton clicks?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13687864/