Friday, January 3, 2014

Implement MouseAdapter for JComponent

Implement MouseAdapter for JComponent
Implement MouseAdapter for JComponent

package javaswingdrawing;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaSwingDrawing extends JComponent {
    
    int mouseX, mouseY;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

    public JavaSwingDrawing() {
        addMouseListener(myMouseAdapter);
    }
    
    MouseAdapter myMouseAdapter = new MouseAdapter(){

        @Override
        public void mousePressed(MouseEvent e) {
            mouseX = e.getX();
            mouseY = e.getY();
            repaint();
        }

    };

    @Override
    public void paint(Graphics g) {
        
        Graphics2D graphics2d = (Graphics2D)g;
        graphics2d.setColor(Color.blue);
        graphics2d.fillOval(mouseX-5, mouseY-5, 10, 10);
    }

    private static void createAndShowGUI() {
        JFrame myFrame = new JFrame();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setSize(new Dimension(400, 300));
        myFrame.setLayout(new BorderLayout());
        myFrame.add(new JavaSwingDrawing(), BorderLayout.CENTER);
        myFrame.setVisible(true);
    }
}



Next: Detect mousePressed and mouseDragged with MouseAdapter

1 comment:

  1. Hi, nice tuto but could I ask that, how to make dont show the initial oval? Thank you.

    ReplyDelete