vendredi 8 mai 2015

MouseListener on a drawString() Method

How can I detect if the text ("Resume", "Restart", "Quit") that I drew with a drawString() method is being clicked?

My code so far:

public class Pause {

    public Pause() {

    }


    public void draw(Graphics2D g) {

        g.setFont(new Font("Arial", Font.BOLD, 14));
        int intValue = Integer.parseInt( "ff5030",16);      
        g.setColor(new Color(intValue));

        g.drawString("Resume", 200, 156);
        g.drawString("Restart", 200, 172);
        g.drawString("Quit", 200, 188);    
    }
}

I hope you can help me. Thanks

@aioobe I tried with your solution:

public void draw(Graphics2D g) {

    g.setFont(new Font("Arial", Font.BOLD, 14));
    int intValue = Integer.parseInt( "ff5030",16);      
    g.setColor(new Color(intValue));

    g.drawString("Resume", 200, 156);
    setResumeRect(g.getFontMetrics().getStringBounds("Resume", g));

    g.drawString("Restart", 200, 172);
    g.drawString("Quit", 200, 188);
}

public void mouseClicked(MouseEvent e) {
    if (getResumeRect().contains(e.getPoint())) {
        System.out.println("clicked");
    }
    System.out.println(getResumeRect());
    System.out.println(e.getPoint());
}

But getResumeRect().contains(e.getPoint()) throws a NullPointerExcpetion.

I also printed resumeRect.contains and mouseEvent.getPoint() with the following result:

java.awt.geom.Rectangle2D$Float[x=0.0,y=-12.902832,w=57.0,h=16.098633] java.awt.Point[x=549,y=470]

Aucun commentaire:

Enregistrer un commentaire