Sainath S.R
Sainath S.R

Reputation: 3306

Can't add ActionListener to a JPanel?

I've been trying for over a hour to test a simple program to change the color of a ball on click , when I try myPanel.addActionListener(new BallListener()), i get one error during compile time

Please help me spot the error?

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

Upvotes: 3

Views: 855

Answers (2)

Mohammadreza Khatami
Mohammadreza Khatami

Reputation: 1332

for panel events you can use WindowListener that's override WindowsClosing Methods , etc ActionListener not used for a Frame or Panel and etc.

Upvotes: 1

khelwood
khelwood

Reputation: 59113

JPanels don't support ActionListeners because they don't have a natural action. For buttons, the natural action is clicking on them, so it makes sense to have an ActionListener that fires when they are clicked. JPanels are not buttons.

If you want to detect clicks on a JPanel, you need to add a MouseListener, not an ActionListener.

Upvotes: 5

Related Questions