Search code examples
javapaintcomponent

Java How to call repaint() on mouse click


So, my code is basically the following:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Test extends JPanel{
    boolean circle = false;

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        this.setBackground(Color.WHITE);

        if(circle){
            g.drawRect(150,150,100,100);
        }
    }

    public static void main(String[] args){
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
        f.setSize(400,400);

        Test test = new Test();
        f.add(test);
    }
}

I want that when I click the mouse, the circle variable changes and it calls repaint().

How can I do this? Thanks.


Solution

  • JPanel.addMouseListener can to achieve it. and notes final keywords is optional in jdk8, when the variable access in inner class.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    class Test extends JPanel {
        boolean circle = false;
    
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            this.setBackground(Color.WHITE);
    
            if (circle) {
                g.drawRect(150, 150, 100, 100);
            }
        }
    
        public static void main(String[] args) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setVisible(true);
            f.setSize(400, 400);
    
            final Test test = new Test();
            test.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    test.circle = true;
                    test.repaint();
                }
            });
            f.add(test);
        }
    }