/** * An extension to JButton that binds the button action to a Driver object, * which must feature a method called buttonPressed() * * @author M. Allen */ import javax.swing.*; import java.awt.event.*; @SuppressWarnings( "serial" ) public class EventButton extends JButton implements ActionListener { private Calculator calculator; /** * pre: Driver d must be instantiated && must contain a method called * buttonPressed(). * post: This button can respond to action events and run the Driver method * buttonPressed(). * * @param d Driver with which this button communicates. */ public EventButton( Calculator c ) { super(); addActionListener( this ); calculator = c; } /** * post: If this button is pressed, the driver method buttonPressed() is * called to respond to the button presss event. * * @param e : ActionEvent from associated objects */ public void actionPerformed( ActionEvent e ) { calculator.buttonPressed( this ); } }
时间: 2023-06-25 10:04:43 浏览: 71
这段代码是一个继承自JButton的类EventButton,它绑定了按钮的操作到一个Calculator对象上,并要求该对象具有名为buttonPressed()的方法。当按钮被按下时,将调用Calculator对象的buttonPressed()方法来响应按钮按下事件。这段代码实现了基本的MVC模式中的控制器部分。
相关问题
The ViewGetBook shows the text field called t (where the user can type text) and a button. Use a grid layout manager to position the two components.
Here's an example code snippet to achieve this using the grid layout manager:
```
import javax.swing.*;
import java.awt.*;
public class ViewGetBook extends JFrame {
private JTextField textField;
private JButton button;
public ViewGetBook() {
// Set up the frame
setTitle("Get Book");
setSize(300, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create the text field and button components
textField = new JTextField();
button = new JButton("Search");
// Set up the grid layout manager
setLayout(new GridLayout(1, 2));
// Add the components to the frame
add(textField);
add(button);
// Show the frame
setVisible(true);
}
public static void main(String[] args) {
ViewGetBook view = new ViewGetBook();
}
}
```
In this code, we create a JFrame and set its title, size, and default close operation. We then create a JTextField and a JButton, and set up a grid layout manager with 1 row and 2 columns. We add the components to the frame, and then make it visible. When we run the program, we should see a frame with a text field and a button positioned side-by-side.
Button cannot be resolved to a type
这个错误提示是因为你在代码中使用了一个类型为 Button 的变量或方法,但是编译器无法找到这个类型的定义。
在 Java 中,Button 是一个类,用于创建图形界面中的按钮控件。如果你想在代码中使用 Button 类型,需要在代码中导入 java.awt 包或 javax.swing 包。
例如,如果你正在使用 javax.swing 包,可以在代码开头添加以下导入语句:
```
import javax.swing.JButton;
```
这样就可以在代码中使用 JButton 类型来创建按钮控件了。请注意,不同的包中可能还有其他类名相同的类型,因此需要根据实际情况选择正确的包和类。