ひとつボタンを作るともう一つ追加することは楽です。これで new で作成したオブジェクトに名前を付ける意味が実感できると思います。イベントを考えると、どちらのボタンを押したのかの判断が必要になります。
カウンタのクリアのボタンを加えることにしましょう。
/** * クリックした回数を数える(クリアボタン付き) */ import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TwoButtons extends JFrame implements ActionListener{ JButton button1; JButton button2; JLabel label; int count = 0; /* コンストラクタ */ public TwoButtons(){ setDefaultCloseOperation(EXIT_ON_CLOSE); //終了処理を追加 button1 = new JButton("Click Me!"); //ボタン1 button2 = new JButton("Clear"); //ボタン2 label = new JLabel("clicks",JLabel.CENTER); //ラベル setLayout(new BorderLayout()); add(button2, BorderLayout.NORTH); add(label, BorderLayout.CENTER); add(button1, BorderLayout.SOUTH); button1.addActionListener(this); button2.addActionListener(this); pack(); setVisible(true); } /* イベントがあったらここに来る */ public void actionPerformed(ActionEvent e) { /* 1つめのボタンだったら */ if (e.getSource() == button1) { count++; } /* 2つめのボタンだったら */ else if (e.getSource() == button2) { count = 0; } label.setText(count + " clicks"); } /********* main **********/ public static void main(String[] args){ /* フレームを作成(事実上のプログラム実行) */ TwoButtons frame1 = new TwoButtons(); } }
上記プログラムをつくりなさい。
数を減らすボタンを加えて3つボタンにしなさい。レイアウトは任意とする。