我正在尝试为我的计算器添加一个ActionListener到我的按钮中。问题是,当我尝试制作ActionListener时,我被提示错误。我尝试了一个类,然后创建了一个侦听器类,以查看是否有帮助。这是我的代码:

package main;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public abstract class Main extends JFrame implements Listener{
public static void main(String[] args) throws IOException{
//Main variables
String dis = "0";
double ans = Double.parseDouble(dis);


 //Making frames
 JFrame frame = new JFrame("Calculator");
 JPanel panel = new JPanel();

 //Buttons
 JButton enter = new JButton("Enter");
 JButton sub = new JButton("-");
 JButton add = new JButton("+");
 JButton div = new JButton("÷");
 JButton mult = new JButton("*");
 JTextField text = new JTextField(dis);

 //Font
 Font bigFont = text.getFont().deriveFont(Font.PLAIN, 30f);
 Font butf = text.getFont().deriveFont(Font.PLAIN, 20f);
 //Methods
 panel.setLayout(new FlowLayout());
 panel.add(text);
 panel.setSize(590, 100);
 text.setColumns(22);
 text.setFont(bigFont);
 text.setHorizontalAlignment(JTextField.RIGHT);
 text.setEditable(false);
 enter.setForeground(Color.RED);
 sub.setForeground(Color.RED);
 div.setForeground(Color.RED);
 mult.setForeground(Color.RED);
 add.setForeground(Color.RED);
 //Buttons Methods
 enter.setBounds(470, 450, 100, 150);
 sub.setBounds(470, 350, 100, 90);
 div.setBounds(470, 250, 100, 90);
 mult.setBounds(470, 150, 100, 90);
 add.setBounds(470, 50, 100, 90);
 enter.setFont(butf);
 sub.setFont(butf);
 div.setFont(butf);
 mult.setFont(butf);
 add.setFont(butf);
 //Frame
 frame.add(div);
 frame.add(mult);
 frame.add(sub);
 frame.add(enter);
 frame.add(add);
 frame.add(panel);
 frame.setSize(600, 650);
 frame.setLocationRelativeTo(null);
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 frame.setVisible(true);


 //extra
 text.setSize(1000, 100);


 //Actions


}
}

package main;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;

public interface Listener extends ActionListener {
//Throwing error here 'Cant instantiate the type ActionListener'
ActionListener al = new ActionListener();
public default void actionPerformed(ActionEvent e){

    }



}


有人知道如何解决此错误吗?

最佳答案

声明一个ActionListener使用

public class Listener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        //dostuff
    }
}

关于java - Java无法实例化类型ActionListener,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33293826/

10-11 17:19