2014-03-19 2 views
1

안녕하세요, 클래스의 구성 요소의 JButton 중 하나를들을 수있게하고 싶습니다. 여기에 JButton이있는 MyPanel 구성 요소가있는 Window 클래스가 있습니다. MyPanel의 JButton을 누를 때 Window에 알림을 보내고 싶습니다. 어떻게해야합니까?구성 요소의 JButton 중 하나를 듣는 방법?

여기는 코드 조각으로 내 필요를 설명하기 위해서만 사용되었으며 테스트되지 않았습니다.

도움 주셔서 감사합니다.

class Window extends JFrame { 
      private MyPanel myPane; 

      public static void main(String [] args) { 
       Window mainWindow = new Window(); 
    } 

    public Window() { 

     this.myPane = new MyPanel(); 
      getContentPane().add(myPane); 

     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     this.setSize(300, 600); 
     this.setVisible(true); 
    } 

     public computations() { 
    // Here I would like to get myPane.s, or do other things regarding myPane's attributes (with getters), only once myPane.b2 is pressed. 
     } 
} 

class MyPanel extends JPanel { 
    String s; 
    JButton b1; 
    JButton b2; 

    public MyPanel() { 
     s = new String(""); 
     b1 = new JButton("say hello"); 
     b2 = new JButton("Close"); 
     this.add(b1); 
     this.add(b2); 
     ButtonHandler phandler = new ButtonHandler(); 
     b1.addActionListener(phandler); 
     b2.addActionListener(actionPerformed(ActionEvent e) { 
      this.s = "Hello world"; 
     }); 

    } 


    class ButtonHandler implements ActionListener { 
     public void actionPerformed(ActionEvent e) { 
      // Tells Window class something happened. 
     } 
    } 

} 

답변

0

나는 당신을 위해 판촉 활동을하고있다. 방금 컴퓨터를 설치하고 아직 Java 환경이나 IDE가 설치되어 있지 않기 때문에 미안하지만 내 솔루션을 테스트 할 수 없습니다.

주요 포인트는 울부 짖는 코드처럼, MyPanel에 윈도우의 인스턴스를 전달할 수 있다는 것입니다 :

class Window extends JFrame { 

     public String myStr = ""; 
     private MyPanel myPane; 

     public static void main(String [] args) { 
      Window mainWindow = new Window(); 
} 

public Window() { 
    this.myPane = new MyPanel(); 
     getContentPane().add(myPane); 

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    this.setSize(300, 600); 
    this.setVisible(true); 
} 

    public computations() { 
// Here I would like to get myPane.s, or do other things regarding myPane's attributes (with getters), only once myPane.b2 is pressed. 
    System.out.println(this.myStr); 
    } 
} 

class MyPanel extends JPanel { 
Window win = null; 
String s; 
JButton b1; 
JButton b2; 

public MyPanel(Window window) { 
    this.win = window; 
    s = new String(""); 
    b1 = new JButton("say hello"); 
    b2 = new JButton("Close"); 
    this.add(b1); 
    this.add(b2); 
    ButtonHandler phandler = new ButtonHandler(); 
    b1.addActionListener(phandler); 
    b2.addActionListener(actionPerformed(ActionEvent e) { 
     this.s = "Hello world"; 
    }); 

} 


class ButtonHandler implements ActionListener { 
    public void actionPerformed(ActionEvent e) { 
     // Tells Window class something happened. 
     this.win.myStr = s; 
    } 
} 

}

+0

가 lowitty 감사가이 방식으로 작동합니다. 그러나 나는 다른 선택의 여지가 있지만 큰 프로그램을 구축하기위한 MVC 패턴에 대해 배울 것 같습니다. – kaligne

관련 문제