【问题标题】:How can I add mouse listener to graphics Polygon?如何将鼠标侦听器添加到图形多边形?
【发布时间】:2023-03-14 13:59:01
【问题描述】:

我想为这个多边形添加一个慕斯监听器。如何将鼠标监听器添加到图形Polygon

public class Domx extends JPanel{

    Domx(){
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        this.setBackground(Color.white);
        Polygon p4=new Polygon();
        for (int i = -1; i < 2; i++) {
                p4.addPoint((int) (X + i * P4[9] / 2), (int) (Y + P1[10] + P2[10] + P3[10] + P4[10]));
        }
        for (int i = 1; i > -2; i--) {
            p4.addPoint((int) (X + i * P4[8] / 2), (int) (Y + P1[10] + P2[10] + P3[10]));
        }
        g2.fillPolygon(p4);
     }
 }

【问题讨论】:

  • 你想用鼠标监听器实现什么?
  • 我想为这个多边形添加一个mousse监听器。 - 你不能直接这样做。您只能将 MouseListener 添加到组件。见安德鲁的回答。如果您想获得花哨的效果,请查看 Playing With ShapesShapeComponent 类,它允许您使用多边形的形状创建组件。

标签: java swing awt java-2d


【解决方案1】:

MouseListener 被添加到组件中,Polygon 是……不是。 而是将鼠标侦听器添加到显示它的组件中,然后当发生鼠标操作时,在继续之前检查是否polygon.contains(..)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-01
    • 2012-07-19
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多