簡體   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