Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my program saying there is an error: "interface expected here"?

Tags:

java

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.");
    }
}
like image 826
TessellatingPi Avatar asked Aug 10 '14 08:08

TessellatingPi


2 Answers

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.

like image 53
afzalex Avatar answered Nov 15 '22 03:11

afzalex


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.

like image 26
christopher Avatar answered Nov 15 '22 04:11

christopher