简体   繁体   English

如何使我的MousePressed侦听器仅在单击特定区域时才响应?

[英]How do I make it so that my MousePressed listener only respons when I click in a certain area?

I have created a simple GUI that has 2 circles and 2 squares. 我创建了一个简单的GUI,具有2个圆和2个正方形。 When the mouse is clicked the shapes change to a random colour. 单击鼠标时,形状将变为随机颜色。 I would like my shapes to only change colour when the mouse has been clicked inside a shape. 我希望形状仅在形状内单击鼠标时才更改颜色。 Also, at the moment all 4 shapes change colour but I wish for each shape to change colour independently depending on which shape is clicked. 另外,目前所有4种形状都会改变颜色,但我希望每种形状都可以根据单击的形状而独立改变颜色。

package weekThree;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;

import javax.swing.*;

@SuppressWarnings("serial")
public class taskTwo2 extends JPanel {
    private static final int PREF_W = 200;
    private static final int PREF_H = PREF_W;
    private Color circleColor = Color.RED;   //starting colour
    private Color circleColor2 = Color.BLUE;
    private Color squareColor = Color.GREEN;
    private Color squareColor2 = Color.YELLOW;
    private int circX  = 10;
    private int circY = circX;
    private int circW = PREF_W - 2 * circX;
    private int circH = PREF_H - 2 * circY;

    public taskTwo2() {
        addMouseListener(new MyMouse()); //mouse click listener
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        // to smooth out graphics
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //smoothes out edges

        g2.setColor(circleColor);
        g2.fillOval(circX, circY, circW, circH);
        g2.setColor(Color.BLACK);
        g2.drawOval(circX, circY, circW, circH);


        g2.setColor(circleColor2);
        g2.fillOval(25*(circX), 25*(circY), circW, circH);
        g2.setColor(Color.BLACK);
        g2.drawOval(25*(circX), 25*(circY), circW, circH);


        g2.setColor(squareColor);
        g2.fillRect(circX, 25*(circY), circW, circH);
        g2.setColor(Color.BLACK);
        g2.drawRect(circX, 25*(circY), circW, circH);


        g2.setColor(squareColor2);
        g2.fillRect(25*(circX), circY, circW, circH);
        g2.setColor(Color.BLACK);
        g2.drawRect(25*(circX), circY, circW, circH);
    }

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

    private class MyMouse extends MouseAdapter {
        Random rand = new Random();

        @Override
        public void mousePressed(MouseEvent e) {
            float red = rand.nextFloat();       //generates a random value for the red tint value
            float green = rand.nextFloat();
            float blue = rand.nextFloat();
            circleColor = new Color(red, green, blue);

            float red2 = rand.nextFloat();
            float green2 = rand.nextFloat();
            float blue2 = rand.nextFloat();
            circleColor2 = new Color(red2, green2, blue2);

            float red3 = rand.nextFloat();
            float green3 = rand.nextFloat();
            float blue3 = rand.nextFloat();
            squareColor = new Color(red3, green3, blue3);

            float red4 = rand.nextFloat();
            float green4 = rand.nextFloat();
            float blue4 = rand.nextFloat();
            squareColor2 = new Color(red4, green4, blue4);

            repaint();   //repaint components
        }
    }

    private static void createAndShowGui() { //code for GUI visuals
        JFrame frame = new JFrame("MyTaskToo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new taskTwo2());
        frame.setSize(500, 500);
        frame.setVisible(true);
    }

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

Thanks 谢谢

You can get the mouse location in your mousePressed() method by using Point mouseLocation = e.getPoint(); 您可以使用Point mouseLocation = e.getPoint();mousePressed()方法中获取鼠标位置Point mouseLocation = e.getPoint(); Then you have to check if the mouse is within the bounds of the circle. 然后,您必须检查鼠标是否在圆的边界内。 The equation for this is simply the Euclidean distance from the center of the circle: 方程就是从圆心到欧几里得距离

/**
 * Checks if the mouse location is within the circle
 * @param mouseLocation the location of the mouse
 * @param cX circle center X location
 * @param cY circle center Y location
 * @param cR circle radius
 * @return true if the mouse is no more than cR units away from the center of the circle 
 */
private static boolean isInCircle(Point mouseLocation, double cX, double cY, double cR){
    final double dX = mouseLocation.getX()-cX;
    final double dY = mouseLocation.getY()-cY;
    return Math.sqrt(dX*dX+dY*dY)<=cR;
}

Then, you just check each circle. 然后,您只需检查每个圆圈。 Here's the code for the first one: 这是第一个的代码:

    if(isInCircle(mouseLocation,circX+circW/2,circY+circH/2,circW/2)){
            float red = rand.nextFloat();       //generates a random value for the red tint value
            float green = rand.nextFloat();
            float blue = rand.nextFloat();
            circleColor = new Color(red, green, blue);
        }

The code for the squares is similar, but it uses the Taxicab distance . 正方形的代码相似,但是使用的是出租车的距离

暂无
暂无

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

相关问题 单击复选框时如何打开一个单独的可编辑框架? - How do I make so when I click my checkbox, a separate and editable frame opens? 如何做到这一点,所以我的编码/解码器仅使用某些ASCII字符 - How can I make it so my encode/decoder only using certain ASCII characters 当我使用JButton时如何停止Java 7中的mousePressed(继续绘制行) - How do I stop mousePressed in Java 7 (line from continuing to be drawn) when I go to use a JButton 仅当用户输入某些值时,如何使程序继续运行? - How do I make my program continue only if the user enters certain values? 如何向CardView添加单击侦听器? - How do I add a click listener to a CardView? 如何在单击时将我的三个按钮 colors 中的一个更改为蓝色,但使其一次只能是蓝色的? - How can I change one of my three buttons colors on click to blue but make it so that only one can be blue at a time? 如何使我的动作侦听器类使用相同的int count变量? - How can I make it so that my action listener classes use the same int count variable? 我如何做才能让我的测验让我回答? - How do I make it so my quiz lets me answer? 如何根据某些情况重复我的程序? - How do I make my program repeat according to certain circumstances? 我试图让我的三角形在我点击鼠标时重新绘制,但是当我点击鼠标时它们只会相乘 - I'm trying to make my triangles redraw themselves when I click the mouse, but they only just multiply when I mouse click
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM