我想在按下按钮时使用Java继续执行工作。当按钮被释放时,工作应该停止。类似这样的:如何在按下按钮时继续执行工作?
Button_is_pressed()
{
for(int i=0;i<100;i++)
{
count=i;
print "count"
}
}
我该如何做到这一点?
我想在按下按钮时使用Java继续执行工作。当按钮被释放时,工作应该停止。类似这样的:如何在按下按钮时继续执行工作?
Button_is_pressed()
{
for(int i=0;i<100;i++)
{
count=i;
print "count"
}
}
我该如何做到这一点?
方式一:
isPressed()
方法和打开或关闭根据其状态的摇摆定时器。前者的一个例子:
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ButtonPressedEg {
public static void main(String[] args) {
int timerDelay = 100;
final Timer timer = new Timer(timerDelay , new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button Pressed!");
}
});
JButton button = new JButton("Press Me!");
final ButtonModel bModel = button.getModel();
bModel.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent cEvt) {
if (bModel.isPressed() && !timer.isRunning()) {
timer.start();
} else if (!bModel.isPressed() && timer.isRunning()) {
timer.stop();
}
}
});
JPanel panel = new JPanel();
panel.add(button);
JOptionPane.showMessageDialog(null, panel);
}
}
我想在按下按钮
执行该进程在另一个线程,然后你的表格是不是继续执行工作块,您可以按按钮取消或停止执行。
看到:
不,我敦促你不要为此使用MouseListener。首先,即使你试图通过禁用JButton来阻止它工作,MouseListener仍然可以工作。通常最好避免在JButton中使用MouseListeners。 –
@Hov我只为最后一句+1。评论的其余部分也是非常好的建议。 –
这是你想要的吗? http://stackoverflow.com/questions/1719166/making-a-jbutton-stay-depressed-manually – AnujKu
我不能说这是一个好主意,主要是因为事件队列的工作方式。如果你阻止当按钮按下时,你将永远不会收到一个鼠标向上事件... – MadProgrammer
没有我想要的是每当用户保持按下按钮,那么一些过程应该开始..当用户离开那个按下按钮,那应该是停止 –