请考虑以下代码。
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.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setSize(500,500);
GUI.setVisible(true);
GUI.setTitle("RobotControl");
}
//The following are declarations of object variables.
private Finch myf;
private JButton front;
private JButton back;
private JButton left;
public RobotControl() {
myf = new Finch();
setLayout (new FlowLayout());
front = new JButton("front");
add(front);
front.addActionListener(new FrontButtonListener(myf));
back = new JButton("back");
add(back);
back.addActionListener(new BackButtonListener(myf));
left = new JButton("left");
add(left);
left.addActionListener(new LeftButtonListener(myf));
}
public class FrontButtonListener implements ActionListener {
public FrontButtonListener(Finch myf) {
// TODO Auto-generated constructor stub
}
public void actionPerformed(ActionEvent arg0) {
myf.setWheelVelocities(100,100,10000);
}
}
public class BackButtonListener implements ActionListener{
public BackButtonListener(Finch myf){
}
public void actionPerformed(ActionEvent arg0) {
myf.setWheelVelocities(-100,-100,10000);
}
}
public class LeftButtonListener implements ActionListener{
public LeftButtonListener(Finch myf){
}
public void actionPerformed(ActionEvent arg0){
myf.setWheelVelocities(0, 200, 1000);
}
现在,上面的代码将创建一个GUI,有三个按钮,前面,后面和左边。我需要一些建议,让程序在运行之前等待所有三个按钮被点击,而不是一次点击一个按钮。
答案 0 :(得分:1)
为每个boolean
创建一个button
变量,在点击其对应按钮时将其设置为true 。
private boolean firstClicked = false;
private boolean secondClicked = false;
private boolean thirdClicked = false;
......
......
//set these boolean values in their onClick actionPerfomed method
if(firstClicked && secondClicked && thirdClicked){
//do whatever operations you want after three buttons have been clicked
}
注意:您需要在Class级别
中拥有这些布尔变量答案 1 :(得分:1)
使用JToggleButton
或JCheckBox
保留每个按钮的状态。假设List<JToggleButton>
名为list
,您可以按如下方式计算allTrue
谓词:
boolean allTrue = true;
for (JToggleButton b : list) {
allTrue &= b.getSelected;
}
仅在allTrue
为true
时启用所需功能。我们看到了一个相关的例子here。
答案 2 :(得分:0)
跟踪已经点击的数量(使用int
)。要执行此操作,请仅在单击尚未单击的按钮时递增int
(您可以使用boolean
跟踪此情况)。当int
等于3时,无论单击按钮的顺序如何,请调用外部方法,该方法执行3 actionPerformed
方法中当前的操作。对于左按钮,这样的东西,以及其他类似的东西:
public void actionPerformed(ActionEvent arg0) {
if(!leftClicked) {
leftClicked = true;
numButtonsClicked++;
}
countLeftButtonClicks++;
if(numButtonsClicked == 3) {
newMethodThatWritesToLogFileToo();
}
}