2016-03-24 9 views
0

基本的に、いくつかのintを持つオブジェクトです。それぞれのボタンが押されたときにintを変更したい。たとえば、JButton 2を押すと、actionPerformedメソッドのif文内のメソッドに基づいて2番目のintが変更されます。私が間違っていたことは確かではありませんが、ボタンはまったく何もしません。ActionListenerで複数のJButtonを使用して.getSource()を使用する方法

public class Object { 

    public int someInt; 
    //public int someOtherInt; 
    //etc. I have a few different ints that I do the same thing with throughout the code, each JButton changes a different int 

    public Object() { 

     this.someInt = someInt; 

     JFrame frame = new JFrame(); 
     frame.setLayout(new FlowLayout()); 
     frame.setDefaultCloseOperation(3); 
     frame.setSize(325, 180); 
     frame.setVisible(true); 
     frame.setTitle("Title"); 

     //String message = blah blah 
     JLabel confirmMessage = new JLabel(message); 
     JButton button1 = new JButton("1"); 
     JButton button2 = new JButton("2"); 
     JButton button3 = new JButton("3"); 

     //creating action listener and adding it to buttons and adding buttons to frame 

    } 

    public class listen implements ActionListener { 

     private int someInt; 
     private int someOtherInt; 

     public listen(int someInt, int someOtherInt) { 

      this.someInt = someInt; 
      this.someOtherInt = someOtherInt; 
     } 

     public void actionPerformed() { 
      if (aE.getSource() == button1) { 
       //change someInt 
      } 
      //same thing for other buttons 
     } 
    } 
} 
+0

これはあなたに働いていた答え –

答えて

0

アクションコマンドを定義し、すべてのボタンに設定します。次に、actionPerformedでそれらを使用して、どのボタンがクリックされたかを判断します。

public class Object { 

    private static final String FIRST_ACTION = "firstAction"; 
    private static final String SECOND_ACTION = "firstAction"; 


    public Object() { 

     JButton button1 = new JButton("1"); 
     button1.setActionCommand(FIRST_ACTION); 

     JButton button2 = new JButton("2"); 
     button2.setActionCommand(SECOND_ACTION); 

     JButton button3 = new JButton("3"); 

     // creating action listener and adding it to buttons and adding buttons 
     // to frame 

    } 

    public class listen implements ActionListener { 

     //some code 

     public void actionPerformed(ActionEvent aE) { 
      if (aE.getActionCommand().equals(FIRST_ACTION)) { 
       // change someInt 
      } else if (aE.getActionCommand().equals(SECOND_ACTION)) { 

      } 
      // same thing for other buttons 
     } 
    } 
} 
+0

を与えるために十分なコードではありません、どうもありがとう –

1

それは、各ボタンに別のリスナーを添付する標準的な方法です:

// syntax for Java 1.8: 
button1.addActionListener(e -> { 
    // do whatever 
}); 

// syntax for Java 1.7 and earlier: 
button1.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
    // do whatever 
    } 
}); 
関連する問題