繁体   English   中英

无法将ActionListener添加到JPanel?

[英]Can't add ActionListener to a JPanel?

我已经尝试了一个多小时测试一个简单的程序来改变点击球的颜色,当我尝试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

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

如果要检测JPanel上的点击,则需要添加MouseListener ,而不是ActionListener

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM