无法将ActionListener添加到JPanel?

3

我已经试了一个小时,想要测试一个简单的程序,在点击时改变球的颜色,但是当我尝试使用myPanel.addActionListener(new BallListener())时,我在编译时遇到了一个错误。

请帮我找出错误所在?

myPanel.addActionListener(new BallListener());
       ^
  symbol:   method addActionListener(Ball.BallListener)
  location: variable myPanel of type MyPanel
1 error





//first Java Program on the new VM
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;

    public class Ball{

    private MyFrame myFrame;
    private MyPanel myPanel;

    public static void main(String[] args)
    {
    Ball ball=new Ball();
    ball.go();

    }//main ends

    public class BallListener implements ActionListener{

    public void actionPerformed(ActionEvent e)
    {
    myFrame.repaint();
    }

    }//listener ends

    public void go()
    {

    myPanel=new MyPanel();
    //myPanel.addActionListener(new BallListener());
    myFrame=new MyFrame();
    myFrame.add(BorderLayout.CENTER,myPanel);
    myFrame.setVisible(true);
    }

    }//class ends



    //ball panel
    class MyPanel extends JPanel
    {
    public void paintComponent(Graphics g)
    {
    Graphics2D g2d=(Graphics2D)g;
    Ellipse2D ellipse=new Ellipse2D.Double(200,200,400,400);
    int r=(int)Math.random()*256;
    int b=(int)Math.random()*256;
    int g1=(int)Math.random()*256;
    Color color=new Color(r,g1,b);
    g2d.setPaint(color);
    g2d.fill(ellipse);
    }
    }//Class ends

    //a simple JFrame
    class MyFrame extends JFrame{

    public MyFrame()
    {
    setSize(600,600);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setResizable(false);
    }
    }//class ends

1
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Seelenvirtuose
2个回答

5

JPanel不支持ActionListener,因为它们没有自然的动作。对于按钮来说,自然的动作是点击,因此有一个在点击时会触发的ActionListener是有意义的。但JPanel不是按钮。

如果你想检测JPanel上的点击事件,你需要添加一个MouseListener而不是ActionListener


1

对于面板事件,您可以使用WindowListener覆盖WindowsClosing方法等。ActionListener不用于Frame或Panel等。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接