2017-11-10 1 views
-1

변수에 하나를 더하고 매 초 JTextField로 출력하는 타이머 프로그래밍을 만들려고합니다. 그러나, 나는 타이머를 시작하고 그것을 계속 버튼을 얻을 수없는 것. 항상 하나를 추가하지만 종료합니다. 시작 버튼을 누를 때마다 타이머가 멈출 때까지 카운팅을 시작하도록 어떻게합니까?JButton에서 루프를 시작하는 방법

// creates timer 
private Timer count; 


public static void main (String[] args) { 
    //inits new timer and GUI 
    timer frame = new timer(); 
    frame.setSize(400,150); 
    frame.createGUI(); 
    frame.setVisible(true); 
} 

//adds start to window 
start = new JButton("Start Timer"); 
    window.add(start); 
    start.addActionListener(this); 

//actionPerformed class 
public void actionPerformed(ActionEvent event) { 


    if(event.getSource() == start) { 
     min1.setText(Integer.toString(time/60)); 
     sec1.setText(Integer.toString(time % 60)); 
     time++; 
     } 
    else { 
     time++; 
    } 

나는 여기에 타이머 버튼으로 시작하고 또한 버튼으로 정지 인 코드 그래서 잘못된 formattings

+0

스윙 타이머를 사용하고 있습니까? 그렇지 않다면 – MadProgrammer

+0

중지 버튼을 잊어 버려야합니다. 먼저 타이머를 시작하고 타이머가 시작될 때마다 1 씩 증가시키는 시작 버튼을 만듭니다. 그런 다음 작업을 마치면 중지 버튼을 추가하십시오. 지금 당장 당신이 추가 한 시작 버튼이나 정지 로직에 문제가 있는지 알 수 없습니다. 문제를 단순화하고 한 번에 한 가지 문제 만 해결하십시오. 더 많은 도움이 필요하면 시작 버튼만으로 적절한 [mcve]를 게시하면 문제가 입증됩니다. – camickr

+0

이것이 더 좋은지 나는 모른다. 그러나 나는 희망한다! –

답변

1

을 exscuse하시기 바랍니다 유래하는 새입니다.

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

class Example implements ActionListener { 
    Timer timer; 
    int count=0; 
    JButton startButton; 
    JButton stopButton; 
    JLabel countLabel; 
    JFrame frame; 
    JPanel contentPane; 

    public Example() { 
     frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     contentPane = new JPanel(); 
     startButton = new JButton("Start"); 
     startButton.addActionListener(this); 

     stopButton = new JButton("Stop"); 
     stopButton.addActionListener(this); 

     countLabel = new JLabel("0"); 

     contentPane.add(startButton); 
     contentPane.add(countLabel); 
     contentPane.add(stopButton); 

     ActionListener listener = new ActionListener() { 

        public void actionPerformed(ActionEvent e) { 
          count++; 
       countLabel.setText(count+""); 
        } 
       }; 
     timer = new Timer(100,listener); 
     frame.setContentPane(contentPane); 
     frame.pack(); 
     frame.setVisible(true); 

    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     if(e.getSource() == startButton) { 
      timer.start(); 
     } 
     if(e.getSource() == stopButton) { 
      timer.stop(); 
     } 
    } 
    public static void main(String args[]) { 
     new Example(); 
    } 
}  
관련 문제