java - MouseListener on a drawString() Method -


how can detect if text ("resume", "restart", "quit") drew drawstring() method being clicked?

my code 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 can me. thanks

@aioobe tried write simple possible. here sscce:

gameframe.java

public class gameframe extends jframe implements runnable {      /**      *       */     private static final long serialversionuid = 1l;       // dimensions     public static final int width = 448;     public static final int height = 288;     public static final double scale = 2.5;       // game thread     private thread thread;     private boolean running;      private int fps = 60;     private long targettime = 1000 / fps;      // image     private bufferedimage image;     private graphics2d g;      //displays     private pause pausedisplay;       public gameframe() {         this.setdefaultcloseoperation(jframe.exit_on_close);         this.setresizable(false);         this.pack();         this.setlocationrelativeto(null);         this.setpreferredsize(new dimension((int)(width * scale), (int)(height * scale)));         this.setbounds(100, 100, (int)(width * scale), (int)(height * scale));         this.setlocationrelativeto(null);         this.setfocusable(true);         this.requestfocus();         this.setvisible(true);     }      public void addnotify() {         super.addnotify();         if(thread == null) {             thread = new thread(this);             thread.start();         }     }      private void init() {                image = new bufferedimage(width, height, bufferedimage.type_int_rgb);         g = (graphics2d) image.getgraphics();          running = true;          }      public void run() {              init();          long start;         long elapsed;         long wait;          // game loop         while(running) {             start = system.nanotime();                       elapsed = system.nanotime() - start;                         wait = targettime - elapsed / 1000000;             if(wait < 0) wait = 5;              try {                 thread.sleep(wait);             }             catch(exception e) {                 e.printstacktrace();             }              pausedisplay = new pause(this);             drawtoscreen();             draw();                  }            }       private void draw() {                        pausedisplay.draw(g);     }       private void drawtoscreen() {         graphics g2 = getgraphics();         g2.drawimage(image, 0, 0, (int)(width * scale), (int)(height * scale), null);         g2.dispose();     }              public static void main(string[] args) {         gameframe game = new gameframe();     }     } 

pause.java

public class pause implements mouselistener{      private rectangle2d resumerect;     private rectangle2d restartrect;      public pause(gameframe gameframe) {         gameframe.addmouselistener(this);     }       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);         resumerect= g.getfontmetrics().getstringbounds("resume", g);          g.drawstring("restart", 200, 172);         restartrect = g.getfontmetrics().getstringbounds("restart", g);          g.drawstring("quit", 200, 188);     }       public void mouseclicked(mouseevent e) {         if (resumerect.contains(e.getpoint())) {             system.out.println("clicked");         }          system.out.println(resumerect);         system.out.println(restartrect);         system.out.println(e.getpoint());     }       public void mousepressed(mouseevent e) {}     public void mousereleased(mouseevent e) {}     public void mouseentered(mouseevent e) {}     public void mouseexited(mouseevent e) {}  } 

you have remember position @ drew string. have 1 rectangle2d each string.

the rectangle of string can computed follows:

rectangle2d r = g.getfontmetrics().getstringbounds(str, g); 

(you need adjust rect position according draw string.)

you register mouse listener checks click coordinates against these rectangles:

if (resumerect.contains(mouseevent.getpoint())) {     ... } 

that being said, i'd recommend reconsider gui code , see if can't use jlabel or jbutton purpose.


regarding edit:

your nullpointerexception due fact can click on frame before image rendered (i.e. before rectangles have been initialized).

apart need 2 edits:

  1. you need take scale account.

    if (resumerect.contains(e.getpoint().getx() / gameframe.scale,                         e.getpoint().gety() / gameframe.scale)) { 

    and

  2. you need compensate fact drawstring draws string on base line, rectangle should lifted base line top left corner of text:

    g.drawstring("resume", 200, 156); resumerect= g.getfontmetrics().getstringbounds("resume", g);  // add this: resumerect.setrect(200,                    156 - g.getfontmetrics().getascent(),                    resumerect.getwidth(),                    resumerect.getheight()); 

Comments