我尝试使用处理程序来完成基于按钮点击的任务。例如,如果按下按钮一次,则必须输出1,或者如果按下按钮两次,则必须输出2。 这必须在5秒内完成。我在android中完成了这个。但是在java中执行它时会出现一些错误。这是等效的Android代码。我想在java中使用Handler实现相同的功能。
@Override
public void onBackPressed() {
if (dblBckToExitPrssdOnce) {
super.onBackPressed();
return;
}
this.dblBckToExitPrssdOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
dblBckToExitPrssdOnce=false;
}
}, 5000);
}
答案 0 :(得分:0)
只需使用标记isFirstClick
即可。如果是(第一次点击),启动计时器(javax.swing.Timer
)。如果计时器在第二次单击之前熄灭,请执行某些操作,例如禁用按钮。如果及时按下按钮,请停止计时器。例如:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class TimedButtonClickDemo {
private JButton button = null;
public TimedButtonClickDemo() {
button = getTimedButton();
JFrame frame = new JFrame();
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public JButton getTimedButton() {
JButton button = new JButton("Press Me");
button.addActionListener(new TimerButtonListener());
return button;
}
private class TimerButtonListener implements ActionListener {
private Timer timer = null;
private boolean isFirstClick = true;
public TimerButtonListener() {
timer = new Timer(5000, new ActionListener(){
public void actionPerformed(ActionEvent e) {
button.setEnabled(false);
System.out.println("Too slow, Jack! Better eat your Wheaties!");
}
});
timer.setRepeats(false);
}
@Override
public void actionPerformed(ActionEvent e) {
if (isFirstClick) {
button.setText("Press Again");
timer.start();
isFirstClick = false;
} else {
timer.stop();
button.setText(" Press Me ");
isFirstClick = true;
System.out.println("You did it. Must be on that Red Bull");
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TimedButtonClickDemo();
}
});
}
}
详情了解如何在How to Use Swing Timers
使用计时器