我正在尝试在RenderCanvas extends类的JPanel对象中按下鼠标时打印控制台。但是,当我在窗口中按下鼠标时,我没有任何反馈。关于我可以进行哪些更改以使MouseListener工作的任何建议?

这是我的代码:

RenderCanvas类:

import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
import java.awt.event.MouseAdapter;


public class RenderCanvas extends JPanel {
    private List<Rect> rectangles = new ArrayList<Rect>();
    private List<Line> lines = new ArrayList<Line>();

    public void renderCanvas() {
        addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                addRect(0, 0, 200, 200, Color.ORANGE);
                System.out.println(e);
            }
        });
    }

    public void paintComponent(Graphics g) {
        for (Rect rectangle : rectangles) {
            rectangle.draw(g);
        }
        for (Line line : lines) {
            line.draw(g);
        }
    }

    public void addRect(int x, int y, int width, int height, Color color) {
        Rect rectangle = new Rect(x, y, width, height, color);
        this.rectangles.add(rectangle);
    }

    public void addLine(int y, int width, Color color) {
        Line line = new Line(y, width, color);
        this.lines.add(line);
    }
}


主类:

import javax.swing.*;
import java.awt.*;
import java.util.Random;

public class Main {
    public static void main(String[] args) {
        JFrame window = new JFrame("Window");
        RenderCanvas canvas = new RenderCanvas();
        window.setContentPane(canvas);
        window.setSize(640, 360);
        window.setLocation(640, 360);
        window.setVisible(true);
    }
}


在此先感谢您的帮助!

最佳答案

public void renderCanvas()不是构造函数。更改

public void renderCanvas()




public RenderCanvas()


注意大写的“ R”和缺少“ void”的返回类型

09-11 17:35