2013-05-30 3 views
0

어떻게해야할지 모르겠다. JButton을 눌렀을 때 메소드 실행을 시작한 다음 다시 클릭하면 해당 메소드가 일시 중지되기를 바란다. 또한 메서드는 계속 실행해야합니다. 지금 내 버튼이 일시 중지되지 않고 시작되지 않으며 계속 실행되지 않습니다.JButton으로 무언가를 시작하고 동일한 JButton으로 일시 정지

private JButton playButton = new JButton("Play!"); 
playButton.addActionListener(new ActionListener(){ 
public void actionPerformed(ActionEvent e) 
{ 
    ????? 
} 

내 문제에 대한 대답은 거기에 있지만 내 시도는 막 깨지지 않는 while 루프로 끝났습니다.

나는 다른 사람에게 물었고 별도의 스레드에서 뭔가를 실행해야한다고 들었다. 문제는 스레드에 대해 아무것도 모릅니다. 쓰래드가 없으면 그것을 할 수있는 다른 방법이 있습니까?

+0

장기 실행 작업 인 경우 스레드를 사용해야하며이 경우에는 그렇습니다. –

+2

[SwingWorker] (http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html)를 사용하여 적절한 [튜토리얼] (http : // docs. oracle.com/javase/tutorial/uiswing/concurrency/worker.html) – Xeon

답변

0

외부 신호에 의해 중지 될 때까지 계속 실행되는 함수/메소드를 구현하면 스레드없이 수행하기가 어렵습니다. GUI 요소의 이벤트 핸들러는 본질적으로 애플리케이션 로직과 별도의 스레드에서 실행됩니다. 두 개가 동시에 실행되면 (즉, 버튼 컨트롤이 클릭 이벤트를 다시 받아 들일 수 있기 전에 일부 처리를 기다리기 때문입니다) ... 응용 프로그램이 빨아 것입니다. 진실한 이야기 ​​형제.

0
boolean running = false; 
private JButton playButton = new JButton("Play!"); 
Thread stuff = new Thread(new RunningThread()); 
playButton.addActionListener(new ActionListener(){ 
public void actionPerformed(ActionEvent e) 
{ 
    if (!running) { 
     stuff.start(); 
     running = true; 
    } 
    else { 
     if (stuff.isAlive()) { 
      stuff.stop(); 
     } 
     running = false; 
    } 

} 

public class RunningThread implements Runnable { 

    public RunningThread() { 
    } 

    @Override 
    public void run() { 
     //DO STUFF: You also want a way to tell that you are finished and that the next button press should start it up again, so at the end make a function like imDone() that sends a message to your page that changes running = false; 
    } 

} 

이와 비슷한 것이 좋습니다. 유일한 문제는 일시 중지가 아니라 중단이라는 것입니다. 일시 정지는 함수 내에서 정확히 무슨 일이 일어나고 있는지에 대해 조금 더 까다로울 수 있습니다.

관련 문제