以下のコードについて質問があります。
質問❶
APIリファレンスを調べたところ、TimerのコンストラクタはTimer(int delay, ActionListener listener)となっております。
Timer timer = new Timer(500, this)のthisはActionListenerを指しているのでしょうか。
質問❷
このthisも同じくActionListenerを指しているのでしょうか。
質問❸
actionPerformedは500ミリ間隔で呼ばれるように設定されていますが、これはあくまでtimerが動いている間で、ストップしている間は動かないですよね。
Java
1package week10; 2 3import java.awt.event.ActionEvent; 4import java.awt.event.ActionListener; 5 6import javax.swing.JButton; 7import javax.swing.JFrame; 8import javax.swing.JLabel; 9import javax.swing.Timer; 10 11public class TimerTest extends JFrame implements ActionListener { 12 13 private static final long serialVersionUID = 1L; 14 15 Timer timer = new Timer(500, this);//質問❶ 16 JLabel label = new JLabel("0", JLabel.CENTER); 17 JButton bt = new JButton("タイマー"); 18 int iCount = 0; 19 20 TimerTest() { 21 setBounds(200, 200, 200, 150); 22 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 23 timer.setActionCommand("timer"); 24 add("North", label); 25 bt.addActionListener(this);//質問❷ 26 add("Center", bt); 27 setVisible(true); 28 } 29 30 public static void main(String[] args) { 31 new TimerTest(); 32 } 33//質問❸ 34 public void actionPerformed(ActionEvent e) { 35 String cmd = e.getActionCommand(); 36 if (cmd.equals("timer")) { 37 if (++iCount > 9) 38 iCount = 0; 39 label.setText(String.valueOf(iCount)); 40 } 41 if (e.getSource() == bt && !timer.isRunning()) 42 timer.start(); 43 else if (e.getSource() == bt && timer.isRunning()) 44 timer.stop(); 45 } 46}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/01/14 11:27
2019/01/14 11:29
2019/01/14 11:43
2019/01/14 11:45
2019/01/14 12:50