我正在从一本书中学习面向对象的编程。我走得很远,但现在我被卡住了。 wExec
重新执行了吗?我不确定这是否可行。有人可以为我清除这一点。当我按下“完成”按钮并退出执行参考对象时,我很困惑。这是每个代码
类:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RunApp {
public static void main(String[] args) {
MainApp app = new MainApp("hello world");
app.showApp();
}
}
class MainApp extends MmvcApp {
WmvcButton btnDone;
WmvcButton btnExit;
public MainApp(String title) {
super(title);
btnDone = new WmvcButton("Done", new WmvcExecutor() {
public void execute(ActionEvent event) {
System.out.println("done");
System.out.println("test 2");
}
});
btnExit = new WmvcButton("Exit", btnDone.getExecutor());
}
}
abstract class MmvcApp {
private static JFrame frame;
private static JPanel panel;
private static MmvcApp singletonApp = null;
public MmvcApp(String frameText) {
singletonApp = this;
initializeApp(frameText);
}
public void initializeApp(String frameText) {
frame = new JFrame(frameText);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setPreferredSize(new Dimension(400, 300));
frame.add(panel, BorderLayout.CENTER);
}
public static JFrame getFrame() {
return frame;
}
public static JPanel getPanel() {
return panel;
}
public static MmvcApp getApp() {
return singletonApp;
}
public void showApp() {
frame.pack();
frame.setVisible(true);
}
}
class WmvcButton extends WmvcController {
private JButton myButton;
public WmvcButton(String compText, WmvcExecutor wExec) {
super((JComponent) new JButton(), wExec);
myButton = (JButton) myComponent;
myButton.setText(compText);
myButton.addActionListener(this);
MmvcApp.getPanel().add(myButton);
}
}
class WmvcController implements ActionListener {
public JComponent myComponent;
private WmvcExecutor wExec;
public WmvcController(JComponent component, WmvcExecutor wExec) {
myComponent = component;
this.wExec = wExec;
}
public WmvcExecutor getExecutor() {
return wExec;
}
public void actionPerformed(ActionEvent event) {
if (wExec != null) {
wExec.execute(event);
System.out.println("test 1");
} else
System.out.println("not working ");
}
}
class WmvcExecutor {
public void execute(ActionEvent event) {
}
}
答案 0 :(得分:1)
btnDone
和btnExit
都与WmvncExecuter
具有相同的引用。在这一行:
btnDone = new WmvcButton("Done", new WmvcExecutor() {
public void execute(ActionEvent event) {
System.out.println("done");
System.out.println("test 2");
}
});
btnExit = new WmvcButton("Exit", btnDone.getExecutor());
您正在覆盖execute()
方法。这与制作一个新课程并在那里重写一样。
class WmvcExecuterTest extends WmvcExecuter{
public void execute(ActionEvent event){
System.out.println("done");
}
}
因此,当您从普通execute()
拨打WmvnExecuter
时,它不会执行任何操作,但是因为您覆盖了execute()
。只要从该特定实例调用execute()
,它就会执行新代码。