我的 Controller - 调用 X 类中的 methodA。 我希望 A 类有一个调用方法 B 的 Jbutton。MethodB 也在 ClassX 中。
基本上这两种方法都会创建 Java Swing 组件,但我希望它们一个接一个地出现(B 仅在单击 A 中的按钮后出现)。
我的 Controller 此时调用:
ClassX.methodA()
ClassX.methodB()
我希望 Controller 仅在 methodA 内单击 JButton 时调用 ClassX.methodA(),然后调用 ClassX.methodB()。
最佳答案
您可以在方法 A 中向按钮添加 Action 监听器,并在处理程序方法内触发方法 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();
}
});
关于java - 仅在第一个方法内单击按钮后才从 Controller 调用两个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30322121/