我一直在尝试找出这段代码的问题,每当我使用ActionListener为convertbutton创建一个事件时,它都会显示这个错误:(我从课本上写了这段代码,它适用于我的大多数同事,但我不知道为什么它不适用于我)
error: cannot find symbol
private class ConvertButtonListener implements ActionListener {
symbol: class ActionListener
location: class KiloConverter
java:37: error: cannot find symbol
public void actionPerformed(ActionEvent e){
symbol: class ActionEvent
location: class KiloConverter.ConvertButtonListener
cannot be converted to ActionListener
convertButton.addActionListener(new ConvertButtonListener());
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
3 errors
The following error occurred while executing this line:
Compile failed; see the compiler error output for details.
BUILD FAILED (total time: 1 second)
下面是我的代码:
myFrame:
package myframe;
import javax.swing.*;
public class MyFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("MyFrame");
frame.setSize(500,500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setTitle("My First Frame");
}
}
KiloConverter:
package myframe;
import java.awt.*;
import javax.swing.*;
public class KiloConverter extends JFrame {
private JPanel panel;
private JButton convertButton;
private JLabel Label;
private JTextField kiloTextField;
final int WINDOW_WIDTH = 400;
final int WINDOW_HEIGHT = 150;
//Constructor
public KiloConverter() {
setTitle("Kilometer Converter");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setLocationRelativeTo(null);
setVisible(true);
}
private void buildPanel(){
panel = new JPanel();
Label = new JLabel("Enter the distance in kilo");
kiloTextField = new JTextField(10);
convertButton = new JButton("Convert");
convertButton.addActionListener(new ConvertButtonListener());
panel.add(Label);
panel.add(kiloTextField);
panel.add(convertButton);
}
private class ConvertButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e){
final double conversion = 0.6214;
String input;
double miles;
input = kiloTextField.getText();
miles = Double.parseDouble(input) * conversion;
JOptionPane.showMessageDialog(null, input+" Kilometer is equal to " + miles +" in miles.");
}
}
public static void main(String[] args){
new KiloConverter();
}
}
发布于 2021-09-29 05:48:25
我认为这是因为您需要使用正确的ActionEvent导入。
导入java.awt.event.ActionListener
。
这应该就行了。
祝您今天愉快!
:D
发布于 2021-09-29 06:50:21
答案可能是因为错误的导入,或者因为您没有这样做。
在这行中:
convertButton.addActionListener(new ConvertButtonListener());
它不会将ActionListener强制转换为"new ConvertButtonListener()“
应该是这样的:
convertButton.addActionListener((ActionListener) new ConvertButtonListener());
试一试,看看问题是否解决了,如果没有解决。这绝对是进口的。
我用我的机器复制了代码,并且工作得很好。所以如果我刚才说的答案不起作用。它必须是进口的。
祝您今天愉快!
如果你有更多的问题,请随时提问!
https://stackoverflow.com/questions/69368329
复制相似问题