2017-12-24 3 views
0

텍스트 필드와 단추가 있어야하는 간단한 창을 만들고 있습니다.ActionListener 클래스 내에서 만든 단추를 사용할 수 없습니다.

public class Find_Suspect_Window extends JFrame{ 

    private JPanel panel=new JPanel(); 
    private JTextField findName = new JTextField("Enter the name"); 
    private JButton findButton = new JButton("Find"); 

    public Find_Suspect_Window() { 

     panel.add(findName); 
     panel.add(findButton); 

     this.setContentPane(panel); 

     FindListener f = new FindListener(); 
     mouse m = new mouse(); 
     findName.addMouseListener(m); 
     findButton.addActionListener(f); 


     this.setVisible(true); 
     this.setSize(300, 100); 
     this.setResizable(false); 
     this.setLocationRelativeTo(null); 
     this.setTitle("Find Suspect"); 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 


    } 

} 

그 다음에 버튼을 가질 수 있도록 ActionListener를 구현하는 동일한 클래스 파일 내에 클래스를 생성합니다.

class FindListener implements ActionListener{ 


    public void actionPerformed(ActionEvent e){ 

     if(e.getSource() == findButton) { 

      String n = findName.getText(); 

     } 

    } 
} 

여기서 findButton을 변수로 확인할 수없고 findName을 확인할 수 없다는 오류가 표시됩니다. 나는 그들이 같은 클래스에 속하지 않는다는 것을 알지만, 버튼을 적절히 기능시키기 위해 필요한 버튼과 필드를 사용해야한다.

내가 뭔가를 놓쳤습니까? 내가 바꾸거나 무언가를 추가해야하는 것이 있습니까?

답변

0

모든 것을 정확하게 기술했다면 아무런 문제가 없어야합니다. 아래 예를 참조하십시오.

class A extends JFrame { 

    private JButton button = new JButton(); 
    private int a; 

    { 
     button.addActionListener (new B()); 
    } 

    class B implements ActionListener { 

     @Override 
     public void actionPerformed (ActionEvent e) { 
      if (e.getSource() == button) { 
       System.out.println (a); 
      } 
     } 

    } 

} 
+0

글쎄, 그래서 내가 이렇게 했어. 작년에 비슷한 임무를 수행 한 것을 기억합니다. 하지만 몇 가지 이유로 지금 나는 그 오류가 발생합니다. 무엇이 잘못되었는지 알아낼 수 없습니다. –

-1

신경 쓰지 마세요. 주 수업의 경계를 벗어난 수업을 만들었습니다. 그래서 변수를 인식하지 못했습니다.

관련 문제