import javax.swing.*; import java.awt.BorderLayout; import java.awt.event.*; public class TimerTest4 extends JFrame implements ActionListener{ Timer timer; JLabel label; int sec; JButton startButton; JButton stopButton; public static void main(String[] args){ TimerTest4 frame = new TimerTest4(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(10, 10, 300, 200); frame.setTitle("タイトル"); frame.setVisible(true); } TimerTest4(){ sec = 0; label = new JLabel(); JPanel labelPanel = new JPanel(); labelPanel.add(label); timer = new Timer(1000 , this); timer.setInitialDelay(5000); startButton = new JButton("start"); startButton.addActionListener(this); startButton.setActionCommand("start"); stopButton = new JButton("stop"); stopButton.addActionListener(this); stopButton.setActionCommand("stop"); stopButton.setEnabled(false); JPanel buttonPanel = new JPanel(); buttonPanel.add(startButton); buttonPanel.add(stopButton); getContentPane().add(labelPanel, BorderLayout.CENTER); getContentPane().add(buttonPanel, BorderLayout.PAGE_END); } public void actionPerformed(ActionEvent e){ if (e.getSource() == timer){ label.setText(sec + " sec"); if (sec >= 10){ stopButton.setEnabled(false); startButton.setEnabled(true); timer.stop(); sec = 0; }else{ sec++; } }else{ String cmd = e.getActionCommand(); if (cmd.equals("start")){ stopButton.setEnabled(true); startButton.setEnabled(false); label.setText("5秒後に開始します"); timer.start(); }else if (cmd.equals("stop")){ stopButton.setEnabled(false); startButton.setEnabled(true); timer.stop(); } } }