0

I am trying to get the console to print when the mouse is pressed within an object of class RenderCanvas which extends JPanel. However, I am getting no feedback when I press the mouse down in the window. Any suggestions as to what I might be able to change to make the MouseListener work?

Here is my code:

RenderCanvas Class:

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);
    }
}

Main Class:

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);
    }
}

Thanks in advance for any help!

3 Answers 3

2

public void renderCanvas() is NOT a constructor. Change

public void renderCanvas()

to

public RenderCanvas()

Notice the upper-case "R" and the absence of the "void" return type

1
1

void RenderCanvas() is not being called. I believe you mean just public RenderCanvas() instead of public void RenderCanvas, since you're only using the ctor in the main method.

0

I think you're intending this method:

public void renderCanvas() {

to be a constructor for the RenderCanvas class; it's not, though, for two reasons: it's not capitalized the same way (small r vs capital R) and also it has a return type. Constructors have no return type; the line should look like

public RenderCanvas() {

Because this isn't a constructor, it's a method, and nobody's calling it, so your event handler is never being added.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.