Can't add ActionListener to JPanel?
I have tried for over an hour to test a simple program to change the color of the ball on click, when I try myPanel.addActionListener(new BallListener())
I get one error at compile time
Please help me find 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
source to share
JPanel
do not support ActionListener
because they have no natural action. For buttons, the natural action is to click on them, so it makes sense to have ActionListener
one that fires when clicked. JPanel
are not buttons.
If you want to detect clicks on JPanel
, you need to add MouseListener
, not ActionListener
.
source to share