2017-10-12 3 views
0

GUI에서 작업 중이며 다른 버튼을 사용하여 다른 작업을 수행하려고합니다.여러 JButton에 여러 actionListener 추가

현재 각 버튼은 동일한 ActionListener로 연결됩니다. 내가 ActionEvent를 쓸

public class GUIController { 

public static void main(String[] args) { 
    javax.swing.SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGUI(); 
     } 
    }); 
} 
public static void createAndShowGUI() { 
    JFrame frame = new JFrame("GUI"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.getContentPane().setLayout(new GridLayout(3,3)); 

    JLabel leight =new JLabel("8"); 
    frame.getContentPane().add(leight); 
    JLabel lfive =new JLabel("0"); 
    frame.getContentPane().add(lfive); 
    JLabel lthree =new JLabel("0"); 
    frame.getContentPane().add(lthree); 

    JButton beight =new JButton("Jug 8"); 
    frame.getContentPane().add(beight); 
    JButton bfive =new JButton("Jug 5"); 
    frame.getContentPane().add(bfive); 
    JButton bthree =new JButton("Jug 3"); 
    frame.getContentPane().add(bthree); 

    LISTN ccal = new LISTN (leight,lfive,lthree); 

    beight.addActionListener(ccal); 
    bfive.addActionListener(ccal); 
    bthree.addActionListener(ccal); 

    frame.pack(); 
    frame.setVisible(true); 

} 

} 

내 된 ActionListener 파일

public class JugPuzzleGUILISTN implements ActionListener { 
JLabel leight; 
JLabel lfive; 
JLabel lthree; 

JugPuzzleGUILISTN(JLabel leight,JLabel lfive, JLabel lthree){ 
    this.leight = leight; 
    this.lfive = lfive; 
    this.lthree = lthree; 
} 

public void actionPerformed(ActionEvent e) { 
    } 

} 
} 

뭐든지 내가 각 버튼은 자신의 기능을 갖도록 할 수있는 방법, 세 개의 버튼에 적용? 정말 고마워요!

+1

'어떻게 각 버튼마다 고유 한 기능을 만들 수 있습니까? '- 각 버튼마다 다른 ActionListener를 추가하십시오. – camickr

+0

단일 리스너를 사용하여'actionCommand' 또는'source' 속성을 사용할 수 있습니다. 당신은'clientProperty'를 사용할 수 있습니다; 각 버튼마다 별도의 리스너를 사용할 수 있습니다. 당신은'Action' API를 사용할 수 있습니다. 잘 정리 된 많은 아이디어들 – MadProgrammer

답변

0

ActionEvent에 쓰는 것은 3 개의 버튼 모두에 적용됩니다. 각 버튼마다 고유 한 기능이 있도록 어떻게 만들 수 있습니까?

3 개의 버튼을 모두 트리거 할 수있는 유사한 동작이 있습니다. 그러나 각 버튼에 대해 구현하려는 다른 기능도 있습니다.

하나의 방법으로 3 개의 리스너가 추가로 생성되어 각각의 버튼에 추가됩니다. 이제 각 버튼에 2 명의 청취자가 추가됩니다 (현재 청취자 + 새로 생성 된 청취자).

//Example: 

beight.addActionListener(ccal); 
bfive.addActionListener(ccal); 
bthree.addActionListener(ccal); 

beight.addActionListener(ccal_beight); 
bfive.addActionListener(ccal_bfive); 
bthree.addActionListener(ccal_bthree); 

이 같은 클릭되는 버튼을 확인하기 위해 현재 리스너의 경우-문을 사용하여 다른 방법이 있습니다,하지만 난 별도의 청취자에게 낮은 코드 커플 링 유지하기 쉽게 찾을 수 있습니다.

2

나는

각 버튼에 다른 ActionListener를 추가 각 버튼은 자신의 기능을 가질 수 있도록 어떻게 그것을 할 수 있습니다.

더 나은 방법은 ActionListener 대신 Action을 사용하는 것입니다. Action은 몇 가지 속성이 추가 된 멋진 ActionListener입니다.

내부 클래스를 정의하는 예제는 How to Use Action의 스윙 튜토리얼에서 각 버튼에 대해 고유 한 Action을 만들 수 있습니다.

관련 문제