使一个方法触发JavaGUI中的另一个方法
考虑以下代码使一个方法触发JavaGUI中的另一个方法,java,swing,events,event-handling,Java,Swing,Events,Event Handling,考虑以下代码 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 { p
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
}
}
}
现在考虑下面的代码,让我的Fink机器人移动10秒。< /P>
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提供反馈,事情会变得相当复杂…下面是一个示例代码:
-------------------------
RobotControl.java
myrobot = new Finch();
foward = new JButton("foward");
add(foward);
forward.addActionListener(new ForwardButtonListener(myrobot));
-------------------------
ForwardButtonListener.java
public class ForwardButtonListener implements ActionListener {
Finch robotToControl;
public FowardButtonListener(Finch aRobot) {
robotToControl = aRobot;
}
public void actionPerformed (ActionEvent e) {
robotToControl.setWheelVelocities(255, 255, 10000);
}
}
-------------------------
1-不使用
myf.sleep(5000)代码>和系统退出(0)代码>在ActionListener
中。2-什么是Finch
?Finch是我用来学习java的一个小机器人。只有谷歌finch机器人。你似乎对ActionListener
s感到困惑。你看了吗?我花了大约10分钟才弄明白你的示例代码,因为你做了一些更改,但它工作得非常完美。你帮了大忙。非常感谢。