简体   繁体   English

您可以在paintComponent中为对象添加鼠标侦听器吗

[英]Can you add a mouse listener to an object in paintComponent

Just a quick question, I was wondering if there is any way to add a mouse listener to a paint component?只是一个简单的问题,我想知道是否有任何方法可以将鼠标侦听器添加到绘图组件? For example, say you drew a rectangle, could you make it so when you click that rectangle, it will then do something.例如,假设你画了一个矩形,你能不能让它当你点击那个矩形时,它会做一些事情。

public void paintComponent(Graphics g) {
    g.drawRect(50, 50, 20, 20);
    //Do something when this rectangle is clicked on
}

To answer your topic question:要回答您的主题问题:

Can you add a mouse listener to an object in paintComponent您可以在paintComponent中为对象添加鼠标侦听器吗

Yes, sort of.是的,有点。 You can't do anything to objects that are declared within the paintComponent method, since their scope is limited to that method, but you can react to objects declared in the class that are drawn within the paintComponent method, and in fact this is commonly done with objects of classes that implement the Shape interface such as Rectangle2D.您不能对在paintComponent 方法中声明的对象做任何事情,因为它们的范围仅限于该方法,但是您可以对在paintComponent 方法中绘制的类中声明的对象做出反应,实际上这通常是这样做的使用实现 Shape 接口的类的对象,例如 Rectangle2D。

For example, run this program, and click on the shapes within it:例如,运行此程序,然后单击其中的形状:

package foo1;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.*;

@SuppressWarnings("serial")
public class GraphicsEg extends JPanel {
    private static final int PREF_W = 400;
    private static final int PREF_H = PREF_W;
    private static final Color SELECTED_COLOR = Color.RED;
    private static final Stroke SELECTED_STROKE = new BasicStroke(8f);
    private List<Shape> shapes = new ArrayList<>();
    private Map<Shape, Color> shapeColorMap = new HashMap<>();
    private Shape selectedShape = null;

    public GraphicsEg() {
        Shape shape = new Ellipse2D.Double(10, 10, 90, 90);
        shapeColorMap.put(shape, Color.GRAY);
        shapes.add(shape);

        shape = new Rectangle2D.Double(140, 140, 200, 200);
        shapeColorMap.put(shape, Color.BLUE);
        shapes.add(shape);

        shape = new RoundRectangle2D.Double(200, 200, 80, 80, 10, 10);
        shapeColorMap.put(shape, Color.GREEN);
        shapes.add(shape);

        addMouseListener(new MyMouseListener());
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        for (Shape shape : shapes) {
            Color color = shapeColorMap.get(shape);
            g2.setColor(color);
            g2.fill(shape);
        }

        if (selectedShape != null) {
            Graphics2D newG2 = (Graphics2D) g2.create();
            newG2.setColor(SELECTED_COLOR);
            newG2.setStroke(SELECTED_STROKE);
            newG2.draw(selectedShape);
            newG2.dispose(); // because this is a created Graphics object
        }
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    private class MyMouseListener extends MouseAdapter {
        @Override
        public void mousePressed(MouseEvent e) {
            for (int i = shapes.size() - 1; i >= 0; i--) {
                if (shapes.get(i).contains(e.getPoint())) {
                    selectedShape = shapes.get(i);
                    repaint();
                    return;
                }
            }
        }
    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("GraphicsEg");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new GraphicsEg());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM