Whenever I type this code, java always underlines the class declaration sentence and the error message is "interface expected here". How can I fix this?
package tempconverter;
import javax.swing.*;
import java.awt.event.*;
import java.awt.FlowLayout;
import static java.lang.System.out;
public class TempConverter extends JFrame implements ActionListener, ActionEvent{
static JFrame f = new JFrame();
static JTextField enter = new JTextField(3);
static JButton confirm = new JButton("Convert");
public static void main(String[] args) {
f.setLayout(new FlowLayout());
f.setSize(100, 50);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(enter);
f.add(confirm);
f.setVisible(true);
}
@Override
public void actionPerformed (ActionEvent e) {
double toConvert = Float.parseFloat(enter.getText());
double inF, inK;
inF = toConvert / 5 * 9 + 32;
inK = toConvert + 273;
out.println("In degrees Fahrenheit, " + toConvert + "degrees Celsius would be " + inF + "degrees.");
out.println("In degrees Kelvin, " + toConvert + "degrees Celsius would be " + inK + "degrees.");
}
}
You are trying to implement a class
ActionEvent
is a class not interface.
And in your program you don't need to extend TempConverter
with JFrame
Hence you can use it as :
public class TempConverter extends ActionEvent implements ActionListener
and to extend ActionEvent
you will need to create a Cunstructor of TempConverter because ActionEvent
is containing a public cunstructor in it.
As per the Java Documentation, ActionEvent
is a class
. You can only implement interfaces
, hence the very clear error message.
What I think you meant..
Normally, when I want to implement some custom ActionListener
, I take a similar approach:
public class MyAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
// Your code here.
}
}
There is no need to take on the methods in ActionEvent
. ActionEvent
is passed in when the event is called. By doing this, you can then access MyAction
as follows:
JButton button = new JButton("Click me!");
button.addActionListener(new MyAction());
And whatever code you put into the actionPerformed
method, will be called on button click.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With