2012-01-17 3 views
2

나는 현재 버튼을 눌렀을 때 배열 요소를 값으로 업데이트 한 다음 그 요소를 포함하는 프레임을 닫는 버튼 집합을 가지고있다.많은 버튼이 비슷한 작업을 수행합니다. actionPerformed를 단순화하는 방법이 있습니까?

현재, 그들의 행동은 다음과 같이 명시되어 있습니다 :

... 
svwnb.addActionListener(new ActionListener(){ 
     public void actionPerformed(ActionEvent e) { 
      input[5] = svwnb.getText(); 
      dftframe.setVisible(false); 
     } 
    }); 
    blypb.addActionListener(new ActionListener(){ 
     public void actionPerformed(ActionEvent e) { 
      input[5] = blypb.getText(); 
      dftframe.setVisible(false); 
     } 
    }); 
    pw91b.addActionListener(new ActionListener(){ 
     public void actionPerformed(ActionEvent e) { 
      input[5] = pw91b.getText(); 
      dftframe.setVisible(false); 
     } 
    }); 
    b97db.addActionListener(new ActionListener(){ 
     public void actionPerformed(ActionEvent e) { 
      input[5] = b97db.getText(); 
      dftframe.setVisible(false); 
     } 
    }); 
    pbepbesolb.addActionListener(new ActionListener(){ 
     public void actionPerformed(ActionEvent e) { 
      input[5] = pbepbesolb.getText(); 
      dftframe.setVisible(false); 
     } 
    }); 
... 

간단한 방법으로이 문제를 단순화하는 방법이 있나요? getSource() 메서드를 사용해야 할 필요가 있지만이 같은 작업 메서드를 작성하는 데 경험이 없습니다.

public void actionPerformed(ActionEvent e){ 
    input[5] = e.getSource().getText(); 
    dftframe.setVisible(false); 
} 

난 그냥이 코드를 생성하는 방법을 정확히 모르는 :

더 간결하기 위해, 나는 코드가 다음 의사처럼 보일 것이라는 생각을 가지고있다.

답변

2

다음과 같은 방법으로 ActionListener를 정의 할 수 있습니다

svnwnb.addActionListener(commonListener); 
... 
+0

@AndrewThompson Yep. 못 생겼어. 질문자는 자신의 수업에서 ActionListener 유형의 (비공개) 필드를 정의 할 수 있습니다. 나는 그것을 편집 할 것이다. 고맙습니다. – MockerTim

+0

고마워요, 이것은 완벽하게 작동했습니다. 많이 감사합니다 – user1147964

+0

@MockerTim 명확히 해주셔서 감사합니다. 좋은 편집, 훌륭한 대답. :) –

1

psudo 코드에 e이 있으면 다른 모든 것이 잘 작동합니다.

input[5] = e.getSource().e.getText(); 
         ^

이 (가 필요하거나하지 않은 경우 확실하지 않음)

input[5] = e.getSource().getText(); 

당신은

input[5] = ((JButton)e.getSource()).getText(); 

이 있습니다 e.getSource()와 같은 뭔가를 추가 캐스트를해야 할 수도 있어야한다 사용할 수있는 ActionEvent의 getActionCommand 메소드도 있지만 버튼에 적절한 actionCommand가 설정된 경우에만 작동합니다.

ActionListener commonListener = new ActionListener() { 

    public void actionPerformed(ActionEvent e) { 
     Object o = e.getSource(); 
     if (o instanceof JTextField) { 
      JTextField textField = (JTextField)o; 
      input[5] = textField.getText(); 
      textField.setVisible(true); 
     } 
    } 
}; 

을 그리고 각 구성 요소에 추가하여 사용 :

+0

제안 된 방식을 사용하면 어떤 구조로이 프로그램을 사용합니까? 각 단추에는 인수 안에 actionPerformed 메서드가있는 .addActionListener가 추가되어 있습니다. 이 문제를 해결하기 위해 프로그램을 어떻게 재구성 할 계획입니까? 고맙습니다. – user1147964

+1

아니요, 여러 행동을 듣지 않아도됩니다. ActionListener 인스턴스를 1 개만 작성해, 같은 액션으로 모든 버튼에 추가합니다. 그런 다음 actionPerformed에서 의사 코드를 사용합니다. –

+0

_ 필수인지 아닌지 확실하지 않은 이유는 무엇입니까? getSource의 유형은 다음과 같이 문서화됩니다 .-) – kleopatra

-1

소스 개체를 다시 찾고 것은 정말 더럽습니다. 그 외에도 출처는 종종 놀랍거나 문서화되지 않았습니다. 그냥 각각의 버튼에 대한 리스너의 다른 인스턴스를 사용합니다.

addTextAction(svwnb); 
    addTextAction(blypb); 
    addTextAction(pw91b); 
    addTextAction(b97db); 
    addTextAction(pbepbesolb); 
    ... 

private void addTextAction(final AbstractButton button) { 
    button.addActionListener(new ActionListener(){ 
     public void actionPerformed(ActionEvent e) { 
      input[5] = button.getText(); 
      dftframe.setVisible(false); 
     } 
    }); 
} 

(텍스트와 버튼을 연결하는 것은 좀 심한 것 같다 그 여기 (분할하는 방법을 분명해야 훨씬 적은 당신이 그것을 해킹하려고 그렇다면) 이벤트 소스를 얻음으로써).

+2

왜 이것이 청취자의 단일 인스턴스보다 낫다고 생각합니까?질문에서 청취자의 목적은 각 필드에 대해 동일합니다. 이벤트 소스 만 다릅니다. – MockerTim

+0

Downvote. 당신의 대답에는 아무것도 아닌 것이 있습니다. 나는 또한 모두가 여기에 downvote에 대한 이유를 설명해야한다고 생각합니다. – MockerTim

관련 문제