Modify the MyFrame class from the code above to extend View, w.In the constructor of MyFrame, the actionPerformed method of the ActionListener of the “Reset” button must call the resetClicked method of the controller c, and the actionPerformed method of the ActionListener of the “Undo” button must call the undoClicked method of the controller c. The controller c will then itself implement the actual meaning of the button clicks. Also move the setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) method call from the constructor of MyFrame to the constructor of View.
时间: 2023-12-03 07:45:17 浏览: 41
Here is the modified code:
```java
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MyFrame extends View {
private Controller c;
private JTextField textField;
public MyFrame(Controller controller) {
super();
this.c = controller;
textField = new JTextField(20);
JButton resetButton = new JButton("Reset");
resetButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
c.resetClicked();
}
});
JButton undoButton = new JButton("Undo");
undoButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
c.undoClicked();
}
});
JPanel panel = new JPanel();
panel.add(textField);
panel.add(resetButton);
panel.add(undoButton);
add(panel, BorderLayout.CENTER);
pack();
setVisible(true);
}
@Override
public void update(String text) {
textField.setText(text);
}
@Override
public void setDefaultCloseOperation() {
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
```
In this modified code, `MyFrame` extends `View` and implements the `update` method. The `Controller` instance is passed to the constructor of `MyFrame`. The `actionPerformed` method of the `ActionListener` of the "Reset" button calls the `resetClicked` method of the `Controller`, and the `actionPerformed` method of the `ActionListener` of the "Undo" button calls the `undoClicked` method of the `Controller`. The `setDefaultCloseOperation` method call has been moved to the constructor of `View`.