将MouseListener添加到面板

将MouseListener添加到面板

本文介绍了将MouseListener添加到面板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将鼠标操作添加到我的面板中。
这是程序应该做的:

I am trying to add the mouse actions to my panel.This is what the program is supposed to do:


推荐答案

我强烈要求建议您首先阅读

Also, Graphics g = panel.getGraphics() isn't how custom painting should be performed. Take a look at Performing custom painting for more details

所以相反,它看起来更像......

So, instead, it might look something more like...

public class TrianglePanel extends JPanel {

    private List<Point> points = new ArrayList<>(3);

    public TrianglePanel() {
        addMouseListener(new MouseListen());
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(200, 200);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.

        if (points.size() < 1) {
            return;
        }
        for (int index = 0; index < points.size(); index++) {
            Point nextPoint = points.get(index);
            g.fillOval(nextPoint.x - 2, nextPoint.y - 2, 4, 4);
        }

        Point startPoint = points.get(0);
        Point lastPoint = startPoint;
        for (int index = 1; index < points.size(); index++) {
            Point nextPoint = points.get(index);
            g.drawLine(lastPoint.x, lastPoint.y, nextPoint.x, nextPoint.y);
            lastPoint = nextPoint;
        }
        g.drawLine(lastPoint.x, lastPoint.y, startPoint.x, startPoint.y);
    }

    class MouseListen extends MouseAdapter {

        public void mouseReleased(MouseEvent e) {
            if (points.size() < 3) {
                points.add(e.getPoint());
                repaint();
            }
        }
    }

}

这篇关于将MouseListener添加到面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 14:07