gpt4 book ai didi

java - 无法将 ActionListener 添加到 JPanel?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:44:52 26 4
gpt4 key购买 nike

我已经尝试了一个多小时来测试一个简单的程序来改变点击时球的颜色,当我尝试 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,因为它们没有自然 Action 。对于按钮,自然的 Action 是点击它们,所以有一个 ActionListener 在它们被点击时触发是有意义的。 JPanel 不是按钮。

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

关于java - 无法将 ActionListener 添加到 JPanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27344947/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com