【问题标题】:Can't add ActionListener to a JPanel?无法将 ActionListener 添加到 JPanel?
【发布时间】:2015-02-05 08:07:18
【问题描述】:

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

【问题讨论】:

  • 您认为面板提供了哪些操作?面板根本不提供任何操作,因此不接受ActionListener。所以没有'addActionListener'方法。

标签: java swing event-handling jpanel actionlistener


【解决方案1】:

JPanels 不支持ActionListeners,因为它们没有自然动作。对于按钮,自然的动作是点击它们,所以有一个ActionListener 在它们被点击时触发是有意义的。 JPanels 不是按钮。

如果您想检测对JPanel 的点击,您需要添加MouseListener,而不是ActionListener

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-13
      • 2014-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多