001:import java.awt.* ;
002:import java.awt.event.* ;
003:import javax.swing.* ;
004:
005:public class MyAction2 {
006:
007: static int count=0; // ボタンの押された回数
008: static JLabel countlabel; // 回数を表示するためのラベル
009:
010: static void countAndDisplay() {
011: count++; //
012: countlabel.setText( "クリック " + count + "回" ); //
013: }
014:
015: public static void main(String args[]) {
016: JFrame frame = new JFrame("Event Test");
017: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
018: Container pane = frame.getContentPane();
019: pane.setLayout( new BorderLayout() );
020:
021: JButton countbutton1 = new JButton("ボタン1"); // 正統派
022: countbutton1.addActionListener(new ActionListener() {
023: public void actionPerformed(ActionEvent e) {
024: countAndDisplay();
025: }
026: });
027:
028: JButton countbutton2 = new JButton("ボタン2"); // actionperformed
029: countbutton2.addActionListener(new ActionListener() {
030: public void actionperformed(ActionEvent e) {
031: countAndDisplay();
032: }
033: });
034:
035: JButton countbutton3 = new JButton("ボタン3"); // MouseEvent
036: countbutton3.addActionListener(new ActionListener() {
037: public void actionPerformed(MouseEvent e) {
038: countAndDisplay();
039: }
040: });
041:
042: JButton countbutton4 = new JButton("ボタン4"); // 3つとも登録
043: countbutton4.addActionListener(new ActionListener() {
044: public void actionperformed(ActionEvent e) {
045: countAndDisplay();
046: }
047: public void actionPerformed(MouseEvent e) {
048: countAndDisplay();
049: }
050: public void actionPerformed(ActionEvent e) {
051: countAndDisplay();
052: }
053: });
054:
055: countlabel = new JLabel( "クリック " + count + "回" );
056: countlabel.setHorizontalAlignment( SwingConstants.CENTER );
057: pane.add( countlabel, BorderLayout.NORTH );
058:
059: JPanel center = new JPanel( new GridLayout(4,1) );
060: center.add( countbutton1 );
061: center.add( countbutton2 );
062: center.add( countbutton3 );
063: center.add( countbutton4 );
064: pane.add( center, BorderLayout.CENTER );
065:
066: frame.pack();
067: frame.setVisible(true);
068: }
069:}