您可以将鼠标侦听器添加到paintComponent中的对象吗? [英] Can you add a mouse listener to an object in paintComponent

查看:92
本文介绍了您可以将鼠标侦听器添加到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
}

推荐答案

要回答您的主题问题:

可以将鼠标侦听器添加到paintComponent中的对象吗?

Can you add a mouse listener to an object in paintComponent

是的,有点.您无法对paintComponent方法中已声明的对象执行任何操作,因为它们的范围仅限于该方法,但是您可以对在paintComponent方法中绘制的类中声明的对象做出反应,实际上,这通常是通过实现Shape接口的类的对象(例如Rectangle2D)完成的.

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.

例如,运行该程序,然后单击其中的形状:

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

这篇关于您可以将鼠标侦听器添加到paintComponent中的对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆