2012-09-01 147 views
4

我想在按下按钮时使用Java继续执行工作。当按钮被释放时,工作应该停止。类似这样的:如何在按下按钮时继续执行工作?

Button_is_pressed() 
{ 
    for(int i=0;i<100;i++) 
    { 
     count=i; 
     print "count" 
    } 
} 

我该如何做到这一点?

+1

这是你想要的吗? http://stackoverflow.com/questions/1719166/making-a-jbutton-stay-depressed-manually – AnujKu

+1

我不能说这是一个好主意,主要是因为事件队列的工作方式。如果你阻止当按钮按下时,你将永远不会收到一个鼠标向上事件... – MadProgrammer

+0

没有我想要的是每当用户保持按下按钮,那么一些过程应该开始..当用户离开那个按下按钮,那应该是停止 –

回答

9

方式一:

  • 到JButton的ButtonModel的
  • 添加一个ChangeListener在这个监听器检查模型的isPressed()方法和打开或关闭根据其状态的摇摆定时器。
  • 如果你想要一个后台进程,那么你可以用相同的方式执行或取消一个SwingWorker。

前者的一个例子:

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); 

    } 
} 
+3

+1不那么复杂,那么我在想 – MadProgrammer

+0

thanx很多..我想要的东西... –

+0

不客气! –

2

您可能需要使用mousePressed事件开始行动

并使用mouseReleased事件停止行动(这个 是neccesary)

欲了解更多信息,请参阅here

+1

不,我敦促你不要为此使用MouseListener。首先,即使你试图通过禁用JButton来阻止它工作,MouseListener仍然可以工作。通常最好避免在JButton中使用MouseListeners。 –

+1

@Hov我只为最后一句+1。评论的其余部分也是非常好的建议。 –

相关问题