2017-11-10 7 views
-1

変数に1を加えて1秒ごとにJTextFieldに出力するタイマープログラミングを作成しようとしています。しかし、私はタイマーを開始し、それを続けるボタンを取得するように見えることはできません。常に1つ追加しますが、終了します。スタートボタンを押すたびに、停止するまでタイマーがカウントを開始するように、どうすればいいですか?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をexscuseください

+0

スイングタイマーを使用していますか?そうでない場合は、 – MadProgrammer

+0

する必要がありますので、停止ボタンを忘れてしまいます。最初に、タイマーを起動するStartボタンを作成し、タイマーが起動するたびに1をインクリメントします。そして、一旦それが働くと、停止ボタンを追加します。あなたが追加したスタートボタンまたはストップロジックに問題があるかどうかは、現在分かりません。問題を簡素化し、一度に1つの問題を解決してください。さらに詳しいヘルプが必要な場合は、[スタート]ボタンだけで適切な[mcve]を投稿すると、問題が示されます。 – camickr

+0

これが良いかどうかわかりませんが、私はそれが願っています! –

答えて

1

、StackOverflowのために新たなんだが、ボタンで起動しても、ボタンで停止されたタイマーのコードです。

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(); 
    } 
}  
関連する問題