2012-07-24 3 views
0

# 내가 게시하고있는 문제에서, 1 행과 2 행에 언급 된 코드를 이해할 수 없습니다. 내가 알고있는 것에 대해 그들이 설정하는 데 사용된다는 것입니다. 버튼에 대한 액션 리스너이지만, 가장 혼란스러운 것은 "JB1.addActionListener (this)"와 같이 라인 1과 라인 2에있는 구문에서 "this"의 역할은 무엇입니까? 이 기본 문법이 어떻게 작동하는지 자세히 설명해주세요. #스윙 : 액션 리스너의 역할

import java.awt.*; 
    import java.awt.event.ActionEvent; 
    import java.awt.event.ActionListener; 

    import javax.swing.*; 



    public class frametest1_1 implements ActionListener 
    { 
     JLabel JL; 
     public frametest1_1() 
     { 
      //create a JFrame container 
      JFrame JF=new JFrame("A BUTTON"); 

      //Frame Layout This is contained in Java .awt.*; "ON USING THIS OPTION OUR BUTTON AND OTHER COMPONENT ARE ADJUSTED IN THE FRAME AUTOMATICALLY" 
      JF.setLayout(new FlowLayout()); 

      //set the size of the container 
      JF.setSize(200, 200); 

      //set visible 
      JF.setVisible(true); 

      //make button 
      JButton JB1=new JButton("FIRST"); 
      JButton JB2=new JButton("SECOND"); 

      //add button to the JFrame container 
      JF.add(JB1); 
      JF.add(JB2); 

      //Create and add Label to the JFrame container 
      JL=new JLabel("PRESS A BUTTON"); 
      JF.add(JL); 

      //set action command :now this will help in determining that which button is presses, is it FIRST or SECOND 
      JB1.setActionCommand("one"); 
      JB2.setActionCommand("two"); 

      //The action responded is added to the actionlistener 
      JB1.addActionListener((ActionListener) this); // line 1 
      JB2.addActionListener((ActionListener) this); // line 2 
     } 

     public void actionPerformed(ActionEvent ae) 
     { 

      if(ae.getActionCommand().equals("one")) 
       JL.setText("First Button Pressed");  // to set text on the label 
      else 
       JL.setText("Second button Pressed"); // to set the text on the label 

     } 
     public static void main(String[] args) 
     { 
      SwingUtilities.invokeLater(new Runnable() 
      { 
       public void run() 
       { 
        new frametest1_1(); 
       } 
      }); 
     } 
    } 
+2

자바 명명 규칙을 배우고 그들에 충실하십시오 : 동일한 기능의

약간 더 나은 구현은 다음과 같은 것이다. – kleopatra

답변

1

1.Listener is someone who reacts to some action 것을 고려하십시오.

2ActionListener 특정 조치가 컨트롤러에서 수행 될 때 실행되는 코드 인 내부 actionPerformed라는 콜백 방법을,있는 인터페이스입니다. 결합/에게 Listener (여기서는 그것의 ActionListener)와 Button 등록한다

JB1 - Button 
    ActionListener - Interface 
    addActionListener - Registering the Button with the Listener. 

4.addActionListener 다음과 같이

3. JB1.addActionListener((ActionListener) this);이 광고 수단. 특정 행동이 그것을 수행하는 MVC 아키텍처 Button is the controller에서는

5.는 모든이 누구 리스너에 등록하여 이루어집니다 어떤 일을 통보한다.

6.

그리고이 리스너는 리스너를 구현하는 클래스에 의해 오버라이드 (override) 이 될 것 callback 방법이있을 것이다. 귀하의 예제에서 또한

7.은 또한 JB1.addActionListener(this);

+0

감사합니다 .....하지만 내가 "this"를 전달하는 매개 변수는 기본적으로 "this"대신에 frametest1_1.if 클래스의 인스턴스입니다.이 클래스의 객체를 frametest1_1처럼 만든 후 전달합니다. obj = new frametest1_1();보다 틀리다 –

+0

"this"는 "현재 객체"를 의미합니다. Runnable 인터페이스를 구현 한 클래스의 인스턴스를 전달하고 있습니다.이 클래스의 객체를 전달할 수 있습니다. , 그러나 당신은 당신이 main() FUNCTION에서 청취자에게 붙인 것과 동일한 객체를 인스턴스화하고 있음을 확신해야합니다. Singleton Pattern을 적용 할 때이 경우에 하나의 객체 만 생성됩니다. –

1

'이'가 둘러싸는 클래스 (frametest1_1)의 현재 인스턴스를 참조 는, 인스턴스가에 건설 ... 이런 식으로 작업을 수행 할 수 있습니다 run() 메소드.

일부 더 '이'에 읽기 : Using the this Keyword

-1

제공 코드 뷰의 객체 지향 설계의 관점에서 정말 추악한 - 따라서 귀하의 혼란.

  • 주요 방법을 포함

따라서 Single responsibility principle을 위반

  • 구현 개념 ActionListener의 (즉 JLabel) JFrame 구성 요소에 대한 참조를 유지
  • 하지만 : 그것은 책임에 대한 하나 개의 클래스를 가지고 확실히 좋은 생각 Swing에 관한 공식 튜토리얼에서도 그러한 추악한 예제를 발견 할 수 있습니다.이 이해하는 데 도움이

    import java.awt.*; 
    import java.awt.event.ActionEvent; 
    import java.awt.event.ActionListener; 
    
    import javax.swing.*; 
    
    public class frametest1_1 { 
    
        public static void main(String[] args) { 
         SwingUtilities.invokeLater(new Runnable() { 
          public void run() { 
           runFrameTest(); 
          } 
         }); 
        } 
    
        public static void runFrameTest() { 
         //create a JFrame container 
         JFrame JF=new JFrame("A BUTTON"); 
    
         //Frame Layout This is contained in Java .awt.*; "ON USING THIS OPTION OUR BUTTON AND OTHER COMPONENT ARE ADJUSTED IN THE FRAME AUTOMATICALLY" 
         JF.setLayout(new FlowLayout()); 
    
         //set the size of the container 
         JF.setSize(200, 200); 
    
         //set visible 
         JF.setVisible(true); 
    
         //make button 
         JButton JB1=new JButton("FIRST"); 
         JButton JB2=new JButton("SECOND"); 
    
         //add button to the JFrame container 
         JF.add(JB1); 
         JF.add(JB2); 
    
         //Create and add Label to the JFrame container 
         final JLabel JL=new JLabel("PRESS A BUTTON"); 
         JF.add(JL); 
    
         //set action command :now this will help in determining that which button is presses, is it FIRST or SECOND 
         JB1.setActionCommand("one"); 
         JB2.setActionCommand("two"); 
    
         ActionListener labelUpdater = new ActionListener() { 
          public void actionPerformed(ActionEvent ae) {    
           if(ae.getActionCommand().equals("one")) 
            JL.setText("First Button Pressed");  // to set text on the label 
           else 
            JL.setText("Second button Pressed"); // to set the text on the label    
          } 
         }; 
         //The action responded is added to the actionlistener 
         JB1.addActionListener(labelUpdater); // line 1 
         JB2.addActionListener(labelUpdater); // line 2 
        } 
    
    } 
    

    희망 ...

  • +1

    GUI를 초기화하는 정적 메서드를 사용하여 객체 지향 패턴을 제공하여 객체 지향 레슨을 제공하고 있습니다. 생성자 나 인스턴스 메소드 중 하나에서 GUI를 생성하는 인스턴스가 있어야합니다. '정적'은 OO 프로그래밍 최악의 ennemy입니다! –

    +0

    Swing에서 'ActionListener'를 올바르게 사용하는 방법 만 설명하려고했지만 내 코드가 OO 관점에서 100 % 완벽하지는 않다는 데 동의합니다. 일반적으로 Swing 기반 응용 프로그램을 구조화하는 방법이 아닙니다. 여기에 사용 된'정적'메소드에 관해서는 - 여기서는 두 가지 이유로 사용했습니다. 1.이 예제는 너무 작아서 별도의 클래스/인스턴스를 만들 수 없습니다. 2. 메인 메소드를 로직으로 오염시키지 않기 위해서. – Yura

    +1

    답변의 첫 번째 문장 : "제공되는 코드는 객체 지향 디자인 관점에서 매우 추악합니다."따라서 객체 지향 디자인 관점에서보기에는 좋지 않은 것을 제공한다고 가정합니다. 두 번째로, 당신이 당신의 예를 너무 작아 객체 지향 설계를 따르지 않는다고 생각하면, 이것은 당신의 대답만큼 유효한 질문을 만든다. 마지막으로, MVC 관점에서 볼 때 이것은 완벽하게 수용 가능합니다. 보기를 만들고 이벤트를 수신 대기하는 컨트롤러 클래스 (frametest_1_1)가 있습니다. 사용자는 주로 'this'와 'ActionListener'의 사용법에 대해 혼란 스럽다고 생각합니다. –

    관련 문제