gpt4 book ai didi

java - 在 Java GUI 中使一个方法触发另一个方法

转载 作者:行者123 更新时间:2023-12-02 06:19:19 24 4
gpt4 key购买 nike

考虑以下代码。

import edu.cmu.ri.createlab.terk.robot.finch.Finch;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class RobotControl extends JFrame {
public static void main (String args[]) {

RobotControl GUI = new RobotControl(); //GUI is the name of my object.
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setSize(300,300);
GUI.setVisible(true);
GUI.setTitle("RobotControl");
}


private JButton foward;



public RobotControl() { //constructor
setLayout (new FlowLayout());

foward = new JButton("foward");
add(foward);

ActionListener e = new event();
foward.addActionListener(e);
}
public class event implements ActionListener {
public void actionPerformed1(ActionEvent e){


}

@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub

}
}

}

现在考虑以下代码,它将使我的雀机器人向前移动 10 秒。

            Finch myf = new Finch();
myf.setWheelVelocities(255, 255, 10000);

现在,我的问题是,通过单击 GUI 上创建的前进按钮,是否可以从第一段代码执行第二段代码?如果是这样我会怎么做。我尝试将 finch 代码放入 actionListener 类中,但没有任何反应。我哪里出错了。我需要建议。

最佳答案

简短的回答是,是的。

首先,您需要维护一个 Finch 实例作为实例变量...

public class RobotControl extends JFrame { 
private Finch finch;
//...
}

您需要创建 Finch 的实例...

public RobotControl {
finch = new Finch();
}

然后在您的ActionListener中,您需要与Finch“通信”

public void actionPerformed1(ActionEvent e){
myf.setWheelVelocities(255, 255, 10000);
}

长答案,您可能必须按顺序发出多个命令,问题是这个过程可能会阻塞事件调度线程,阻止响应新传入的事件并使其看起来就像您的应用程序已“停止”

虽然有多种方法可以缓解这个问题,但如果您不需要 Finch 与 UI 进行通信(例如报告电机状态或其他内容),您可以简单地使用一个某种类型的线程Executor,并通过它简单地发出一系列命令。

如果您需要向客户端 UI 提供反馈,事情就会变得更加复杂......

关于java - 在 Java GUI 中使一个方法触发另一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21151147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com