2014-05-17 4 views
0

그래서 기본적으로 타이머를 시작하기 위해 jpanel에서 키 바인딩을 사용합니다. 키 바인드를 다시 사용하는 방법을 알아 내려고했지만 타이머가 계속 증가하는 동안 카운트를 늘리는 중입니다.동시에 타이머와 키 바인딩

m2.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke 
(KeyEvent.VK_LEFT,0,true),"left"); 
    m2.getActionMap().put("left",new Actions()); 


public void Timer(boolean startTimer){ 
    if(startTimer==true){ 
     long staTime = System.currentTimeMillis(); 
     while(startTimer==true){ 
      System.out.println(System.currentTimeMillis()/1000.0-staTime/1000.0); 
     } 
    } 
} 

public class Actions extends AbstractAction { 

private static final long serialVersionUID = 1L; 
int start = 0; 
int count = 0; 
    public void actionPerformed(ActionEvent e) { 
     Begin b = new Begin(); 
     if(start==0){ 
      start++; 
      b.Timer(true); 
     } 
     count++; 
     System.out.println(count); 
     if(count==10){ 
      b.Timer(false); 
     } 

} 
+0

당신은 타이머를 시작하는 순간을 실현 할, 당신은 이벤트 파견 스레드를 차단하고 프로그램이 내가하려고 메신저 알고 완전한 재고 ... – MadProgrammer

+0

아에 와서 원인이 있습니다 : 다음은 간단한 예입니다 디스패치 스레드를 차단하지 않고 타이머를 유지하는 방법 알아보기 – NickPali

답변

0

나는 그 코드가 무엇을 하려는지 전혀 모른다. 자신 만의 타이머를 만들려고하는 것 같습니다. 스윙은 이미 Timer 클래스를 가지고 있으므로 바퀴를 재발 명하지 마십시오.

자세한 내용은 How to Use Swing Timers의 스윙 튜토리얼 섹션을 참조하십시오. Swing Timer API에는 Timer가 실행되는 간격을 동적으로 변경할 수있는 메서드가 있습니다.

자습서의 타이머 예제는 비교적 복잡합니다.

import java.awt.*; 
import java.awt.event.*; 
import java.util.*; 
import javax.swing.*; 
import javax.swing.Timer; 

public class TimerTime extends JPanel implements ActionListener 
{ 
    private JLabel timeLabel; 

    public TimerTime() 
    { 
     timeLabel = new JLabel(new Date().toString()); 
     add(timeLabel); 

     Timer timer = new Timer(1000, this); 
     timer.setInitialDelay(1); 
     timer.start(); 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) 
    { 
     //System.out.println(e.getSource()); 
     timeLabel.setText(new Date().toString()); 
    } 

    private static void createAndShowUI() 
    { 
     JFrame frame = new JFrame("TimerTime"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.add(new TimerTime()); 
     frame.setLocationByPlatform(true); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) 
    { 
     EventQueue.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       createAndShowUI(); 
      } 
     }); 
    } 
} 
+0

이미 스윙 타이머가 있음을 알았습니다. – NickPali