只有在第一个方法内点击按钮后才能从Controller调用两个方法

时间:2015-05-19 09:47:29

标签: java swing

我的控制器 - 在类X中调用methodA。 我希望A类有一个Jbutton调用方法B. MethodB也在ClassX中。

基本上两种方法都会创建Java Swing组件,但我希望它们一个接一个地出现(B仅在A中按钮单击后出现。)

我的控制器此刻打电话:

 <table>
      <tr>
        <th>Poem</th>
        <th>Poem</th>
      </tr>
      <tr>
        <td nowrap><h4>Never increase, beyond what is necessary</h4></td>
        <td>Never increase, beyond what is necessary, the number of entities required to explain anything</td>
      </tr>
</table>

我会以某种方式让控制器调用ClassX.methodA(),然后在方法A中单击JButton时调用ClassX.methodB()。

1 个答案:

答案 0 :(得分:1)

您可以将actionlistener添加到方法A中的按钮,并在处理程序方法内部触发方法B

    JButton button = new JButton(" Method A");
    //Add action listener to button
    button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e)
        {
            //Execute when button is pressed
            methodB();
        }
    });   

或者,(推荐方式)您可以将Controller作为A类的观察者,因此当单击该按钮时,您通知Controller触发方法B

    JButton button = new JButton(" Method A");
    //Add action listener to button
    button.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e)
        {
            //Execute when button is pressed
            //Notify controller that method A is clicked
            notifyObserver();
        }
    });