java 是否有可能:通过方法调用触发 JButton 事件 - 而不是 JButton 点击?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13687864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible: trigger JButton events via method call - not JButton clicks?
提问by Saleh Feek
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 questionabout 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.
当客户端单击 GUI 中的按钮时。
发送到服务器端的字符串“A”。
当服务器从客户端收到字符串“A”时,它会调用“methodA”;methodA 调用会
影响服务器端的 GUI。以便客户端和服务器 GUI 相应更新。
Thank you.
谢谢你。
回答by Qwerky
JButton
has a doClick()
method inherited from AbstractButton
.
JButton
有一个doClick()
方法继承自AbstractButton
.
http://docs.oracle.com/javase/6/docs/api/javax/swing/AbstractButton.html#doClick
http://docs.oracle.com/javase/6/docs/api/javax/swing/AbstractButton.html#doClick
which means you can simply write
这意味着你可以简单地写
game.leftButton.doClick();