Question

So I am trying to implement a mouse listener into my program, I got the mouseListener to work but not the graphics. I am trying to find a way to draw a blue circle every time the mouse is clicked on the JPANEL, the only problem is I can not seem to get a good call for the Graphics (that I have tried to name g).

    import java.awt.*;
import java.awt.event.*;

import javax.swing.JFrame;
import javax.swing.JPanel;



class moveItMon extends JPanel implements MouseListener{

    public moveItMon() {
        this.setPreferredSize(new Dimension(500, 500));
        addMouseListener(this);
    }

    public void addNotify() {
        super.addNotify();
        requestFocus();
    }

    public void mouseClicked(MouseEvent e){}
    public void mouseExited(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mousePressed(MouseEvent e){}
    public void mouseReleased(MouseEvent e) {
        movetehMon(e);
    }

    public void movetehMon(MouseEvent e){
        int x = e.getX();
        int y = e.getY();
        System.out.println("(" + x + "," + y + ")");
        paintMon(x,y);
    }
    public void paintMon( int x, int y){
        Graphics g = new Graphics();
        g.setColor(Color.WHITE);
        g.clearRect(0,0,500,500);
        g.setColor(Color.BLUE);
        g.fillOval(x,y,20,20);
    }

    public static void main(String[] s) {
        JFrame f = new JFrame("moveItMon");
        f.getContentPane().add(new moveItMon());
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }


}
Was it helpful?

Solution

Graphics g = new Graphics(); isn't going to work (as I'm sure you're aware) as the class is abstract.

Custom painting in Swing is done by overriding the paintComponent of a component that extends from JComponent (like JPanel) and using the supplied Graphics context to paint to.

Take a look at Performing Custom Painting and Painting in AWT and Swing for more details

You should also beware that painting is a destructive process, meaning that each time paintComponent is called, you are expected to update everything that you need painted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top