Adding mouse listener to a frame

Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Nov 2006
Posts: 27
Reputation: anti_genius is an unknown quantity at this point 
Solved Threads: 0
anti_genius anti_genius is offline Offline
Light Poster

Adding mouse listener to a frame

 
0
  #1
Nov 21st, 2006
Hi,

Can someone tell me how i can implement a mouselistener interface on a frame.

I have a program that loads an image on a canvas. now i want to get the screen coordinate where user clicks on the image. I can do this using an applet but i want to do it with awt frame.

Can someone tell me?

Regards
Reply With Quote Quick reply to this message  
Join Date: Nov 2004
Posts: 6,143
Reputation: jwenting is just really nice jwenting is just really nice jwenting is just really nice jwenting is just really nice 
Solved Threads: 213
Team Colleague
jwenting's Avatar
jwenting jwenting is offline Offline
duckman

Re: Adding mouse listener to a frame

 
0
  #2
Nov 21st, 2006
It's no different...
As people are clearly allowed to attack me but I'm not allowed to defend myself, I no longer post to this site.
Reply With Quote Quick reply to this message  
Join Date: Nov 2006
Posts: 27
Reputation: anti_genius is an unknown quantity at this point 
Solved Threads: 0
anti_genius anti_genius is offline Offline
Light Poster

Re: Adding mouse listener to a frame

 
0
  #3
Nov 21st, 2006
Originally Posted by jwenting View Post
It's no different...
This is not a private message !!

I tried the applet code on frame but it didn't work. That's why asked if someone could help.
Reply With Quote Quick reply to this message  
Join Date: Mar 2004
Posts: 765
Reputation: Phaelax is on a distinguished road 
Solved Threads: 38
Phaelax Phaelax is offline Offline
Master Poster

Re: Adding mouse listener to a frame

 
0
  #4
Nov 21st, 2006
What exactly didn't work? Code should be the same.

public class MyFrame extends Frame implements MouseListener

//include methods found in the MouseListener interface
Reply With Quote Quick reply to this message  
Join Date: Nov 2006
Posts: 27
Reputation: anti_genius is an unknown quantity at this point 
Solved Threads: 0
anti_genius anti_genius is offline Offline
Light Poster

Re: Adding mouse listener to a frame

 
0
  #5
Nov 22nd, 2006
Originally Posted by Phaelax View Post
What exactly didn't work? Code should be the same.

public class MyFrame extends Frame implements MouseListener

//include methods found in the MouseListener interface
Yes i did the same. But the program did not respond to the mouse events. Nothing happened.
Reply With Quote Quick reply to this message  
Join Date: Mar 2004
Posts: 765
Reputation: Phaelax is on a distinguished road 
Solved Threads: 38
Phaelax Phaelax is offline Offline
Master Poster

Re: Adding mouse listener to a frame

 
0
  #6
Nov 23rd, 2006
Post your code then. (in code tags)
Reply With Quote Quick reply to this message  
Join Date: Nov 2004
Posts: 6,143
Reputation: jwenting is just really nice jwenting is just really nice jwenting is just really nice jwenting is just really nice 
Solved Threads: 213
Team Colleague
jwenting's Avatar
jwenting jwenting is offline Offline
duckman

Re: Adding mouse listener to a frame

 
0
  #7
Nov 23rd, 2006
Originally Posted by anti_genius View Post
This is not a private message !!
If it had been you'd not have gotten a response at all...

I tried the applet code on frame but it didn't work. That's why asked if someone could help.
It does work the same, but you may be confused about the way it works in applets and not realise it...
Last edited by jwenting; Nov 23rd, 2006 at 3:06 pm.
As people are clearly allowed to attack me but I'm not allowed to defend myself, I no longer post to this site.
Reply With Quote Quick reply to this message  
Join Date: Nov 2006
Posts: 27
Reputation: anti_genius is an unknown quantity at this point 
Solved Threads: 0
anti_genius anti_genius is offline Offline
Light Poster

Re: Adding mouse listener to a frame

 
0
  #8
Nov 24th, 2006
Originally Posted by Phaelax View Post
Post your code then. (in code tags)
Its a long code but i hope u can easilt find the mouse events.

  1.  
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import java.awt.image.*;
  5. class ImgMod3 extends Frame implements MouseListener {
  6. String msg = "";
  7. int mX = 0;
  8. int mY = 0;
  9. Image rawImg;
  10. int imgCols;//Number of horizontal pixels
  11. int imgRows;//Number of rows of pixels
  12. Image modImg;//Reference to modified image
  13. //Inset values for the Frame
  14. int inTop;
  15. int inLeft;
  16. //To add only one picture at a time
  17. int ig = 1;
  18. //This program will be executed to process the
  19. // if the name of another program is not
  20. // entered on the command line.
  21. static String theProcessingClass = "PrintMouse";
  22. // This image file will be processed if another file name is
  23. // not entered on the command line.
  24. static String theImgFile = "white.gif";
  25. MediaTracker tracker;
  26. Display display = new Display();//A Canvas
  27. Button replotButton = new Button("Replot");
  28. //References to arrays that store pixel data.
  29. int[][][] threeDPix;
  30. int[][][] threeDPixMod;
  31. int[] oneDPix;
  32. //Reference to the image-processing object.
  33. ImgIntfc02 imageProcessingObject;
  34. //-------------------------------------------//
  35. public static void main(String[] args){
  36. // Program supports gif files and jpg files
  37. // and possibly some other file types as well.
  38. if(args.length == 0){
  39. //Use default processing class and default image file. No code required here.
  40. // Class and file names were specified above.
  41. }else if(args.length == 1){
  42. theProcessingClass = args[0];
  43. //Use default image file
  44. }else if(args.length == 2){
  45. theProcessingClass = args[0];
  46. theImgFile = args[1];
  47. }else{
  48. System.out.println("Invalid args");
  49. System.exit(1);
  50. }//end else
  51. //Display name of processing program and
  52. // image file.
  53. System.out.println("Processing program: " + theProcessingClass);
  54. System.out.println("Image file: " + theImgFile);
  55. //Instantiate an object of this class
  56. ImgMod3 obj = new ImgMod3();
  57. }//end main
  58. //-------------------------------------------//
  59. public ImgMod3(){//constructor
  60. //Get an image from the specified file. Can
  61. // be in a different directory if the path
  62. // was entered with the file name on the command line.
  63. rawImg = Toolkit.getDefaultToolkit().getImage(theImgFile);
  64. //Use a MediaTracker object to block until
  65. // the image is loaded or ten seconds has elapsed.
  66. tracker = new MediaTracker(this);
  67. tracker.addImage(rawImg,1);
  68. try{
  69. if(!tracker.waitForID(1,10000)){
  70. System.out.println("Load error.");
  71. System.exit(1);
  72. }//end if
  73. }catch(InterruptedException e){
  74. e.printStackTrace();
  75. System.exit(1);
  76. }//end catch
  77. //Make certain that the file was successfully
  78. // loaded.
  79. if((tracker.statusAll(false) & MediaTracker.ERRORED & MediaTracker.ABORTED) != 0){
  80. System.out.println("Load errored or aborted");
  81. System.exit(1);
  82. }//end if
  83. //Raw image has been loaded. Get width and
  84. // height of the raw image.
  85. imgCols = rawImg.getWidth(this);
  86. imgRows = rawImg.getHeight(this);
  87. this.setTitle("Copyright 2004, Baldwin");
  88. this.setBackground(Color.YELLOW);
  89. this.add(display);
  90. this.add(replotButton,BorderLayout.SOUTH);
  91. //Make it possible to get insets and the
  92. // height of the button.
  93. setVisible(true);
  94. //Get and store inset data for the Frame and
  95. // the height of the button.
  96. inTop = this.getInsets().top;
  97. inLeft = this.getInsets().left;
  98. int buttonHeight = replotButton.getSize().height;
  99. //Size the frame so that a small amount of
  100. // yellow background will show on the right
  101. // and on the bottom when both images are
  102. // displayed, one above the other. Also, the
  103. // placement of the images on the Canvas
  104. // causes a small amount of background to
  105. // show between the images.
  106. this.setSize(inLeft+imgCols + 1,inTop + buttonHeight + imgRows + 7);
  107. addMouseListener(this);
  108. //=========================================//
  109. //Anonymous inner class listener for replot
  110. // button. This actionPerformed method is
  111. // invoked when the user clicks the Replot
  112. // button. It is also invoked at startup
  113. // when this program posts an ActionEvent to
  114. // the system event queue attributing the
  115. // event to the Replot button.
  116. replotButton.addActionListener(
  117. new ActionListener(){
  118. public void actionPerformed(ActionEvent e){
  119. //Pass a 3D array of pixel data to the
  120. // processing object and get a modified 3D array of pixel data back.
  121. threeDPixMod = imageProcessingObject.processImg(threeDPix,imgRows,imgCols);
  122. //Convert the modified pixel data to a
  123. // 1D array of pixel data.
  124. oneDPix = convertToOneDim(threeDPixMod,imgCols,imgRows);
  125. //Use the createImage() method to
  126. // create a new image from the 1D array of pixel data.
  127. modImg = createImage(new MemoryImageSource(imgCols,imgRows,oneDPix,0,imgCols));
  128. //Repaint the image display frame with
  129. // the original image at the top and
  130. // the modified pixel data at the bottom.
  131. display.repaint();
  132. }//end actionPerformed
  133. }//end ActionListener
  134. );//end addActionListener
  135. //End anonymous inner class.
  136. //=========================================//
  137. //Create a 1D array object to receive the
  138. // pixel representation of the image
  139. oneDPix = new int[imgCols * imgRows];
  140. //Convert the rawImg to numeric pixel
  141. // representation. Note that grapPixels()
  142. // throws InterruptedException
  143. try{
  144. //Instantiate a PixelGrabber object
  145. // specifying oneDPix as the array in which
  146. // to put the numeric pixel data.
  147. PixelGrabber pgObj = new PixelGrabber(rawImg,0,0,imgCols,imgRows, oneDPix,0,imgCols);
  148. //Invoke the grabPixels() method on the
  149. // PixelGrabber object to extract the pixel
  150. // data from the image into an array of
  151. // numeric pixel data stored in oneDPix.
  152. if(pgObj.grabPixels() && ((pgObj.getStatus() & ImageObserver.ALLBITS)!= 0)){
  153. //Convert the pixel byte data in the 1D
  154. // array to int data in a 3D array to
  155. // make it easier to work with the pixel
  156. // data later. Recall that pixel data is
  157. // unsigned byte data and Java does not
  158. // support unsigned arithmetic.
  159. threeDPix = convertToThreeDim(oneDPix,imgCols,imgRows);
  160. //Instantiate a new object of the image
  161. // processing class. Note that this
  162. // object is instantiated using the
  163. // newInstance method of the class named
  164. // Class. This approach does not support
  165. // the use of a parameterized
  166. // constructor.
  167. try{
  168. imageProcessingObject = (ImgIntfc02)Class.forName(theProcessingClass).newInstance();
  169. //Post counterfeit ActionEvent to the
  170. // system event queue and attribute it
  171. // to the Replot button. Posting this event causes
  172. // the image-processing method to be
  173. // invoked, passing the 3D array of pixel data to the method, and receiving a 3D array of modified
  174. // pixel data back from the method.
  175. Toolkit.getDefaultToolkit().
  176. getSystemEventQueue().postEvent(new ActionEvent(replotButton, ActionEvent.ACTION_PERFORMED, "Replot"));
  177. //At this point, the modified image
  178. // have been displayed.
  179. }catch(Exception e){
  180. System.out.println(e);
  181. }//end catch
  182. }//end if statement on grabPixels
  183. else System.out.println("Pixel grab not successful");
  184. }catch(InterruptedException e){
  185. e.printStackTrace();
  186. }//end catch
  187. //Cause the composite of the frame, the
  188. // canvas, and the button to become visible.
  189. this.setVisible(true);
  190. //=========================================//
  191. //Anonymous inner class listener to terminate
  192. // program.
  193. this.addWindowListener(
  194. new WindowAdapter(){
  195. public void windowClosing(WindowEvent e){
  196. System.exit(0);//terminate the program
  197. }//end windowClosing()
  198. }//end WindowAdapter
  199. );//end addWindowListener
  200. //=========================================//
  201. }//end constructor
  202. //===========================================//
  203. public void mouseClicked(MouseEvent me) {
  204. mX = 0;
  205. mY = 10;
  206. msg = "Mouse clicked";
  207. //repaint();
  208. System.out.println("mY = " + mY);
  209. }
  210. public void mouseEntered(MouseEvent me) {
  211. mX = 0;
  212. mY = 10;
  213. msg = "Mouse entered";
  214. repaint();
  215. }
  216. public void mouseExited(MouseEvent me) {
  217. mX = 0;
  218. mY = 10;
  219. msg = "Mouse exited";
  220. repaint();
  221. }
  222. public void mousePressed(MouseEvent me) {
  223. mX = me.getX();
  224. mY = me.getY();
  225. msg = "Down";
  226. repaint();
  227. }
  228. public void mouseReleased(MouseEvent me) {
  229. mX = me.getX();
  230. mY = me.getY();
  231. msg = "Up";
  232. repaint();
  233. }
  234. public void paint(Graphics g) {
  235. g.drawString(msg + " " + mX + " " + mY, mX, mY);
  236. }
  237. ///Inner class for canvas object on which to
  238. // display the two images.
  239. class Display extends Canvas
  240. {
  241. //Override the paint method to display both
  242. // the rawImg and the modImg on the same
  243. // Canvas object, separated by one row of
  244. // pixels in the background color.
  245. public void paint(Graphics g)
  246. {
  247. //First confirm that the image has been
  248. // completely loaded and neither image
  249. // reference is null.
  250. if (tracker.statusID(1, false) == MediaTracker.COMPLETE)
  251. {
  252. if ((rawImg != null) && ig==1)
  253. {
  254. g.drawImage(rawImg, 0, 0, this);
  255. ig = 2;
  256. //g.drawImage(modImg, 0, imgRows + 1, this);
  257. }//end if
  258. else if((modImg!=null) && ig==2)
  259. {
  260. g.drawImage(modImg, 0, 0, this);
  261. }
  262. }//end if
  263. }//end paint()
  264. }//end class myCanvas
  265. //=============================================//
  266. //Save pixel values as type int to make
  267. // arithmetic easier later.
  268. //The purpose of this method is to convert the
  269. // data in the int oneDPix array into a 3D
  270. // array of ints.
  271.  
  272. int[][][] convertToThreeDim(
  273. int[] oneDPix,int imgCols,int imgRows){
  274. //Create the new 3D array to be populated
  275. // with color data.
  276. int[][][] data = new int[imgRows][imgCols][4];
  277. for(int row = 0;row < imgRows;row++){
  278. //Extract a row of pixel data into a
  279. // temporary array of ints
  280. int[] aRow = new int[imgCols];
  281. for(int col = 0; col < imgCols;col++){
  282. int element = row * imgCols + col;
  283. aRow[col] = oneDPix[element];
  284. }//end for loop on col
  285. //Move the data into the 3D array. Note
  286. // the use of bitwise AND and bitwise right
  287. // shift operations to mask all but the
  288. // correct set of eight bits.
  289. for(int col = 0;col < imgCols;col++){
  290. //Alpha data
  291. data[row][col][0] = (aRow[col] >> 24) & 0xFF;
  292. //Red data
  293. data[row][col][1] = (aRow[col] >> 16) & 0xFF;
  294. //Green data
  295. data[row][col][2] = (aRow[col] >> 8) & 0xFF;
  296. //Blue data
  297. data[row][col][3] = (aRow[col]) & 0xFF;
  298. }//end for loop on col
  299. }//end for loop on row
  300. return data;
  301. }//end convertToThreeDim
  302. //-------------------------------------------//
  303. //The purpose of this method is to convert the
  304. // data in the 3D array of ints back into the
  305. // 1d array of type int. This is the reverse
  306. // of the method named convertToThreeDim.
  307. int[] convertToOneDim(int[][][] data,int imgCols,int imgRows){
  308. //Create the 1D array of type int to be
  309. // populated with pixel data, one int value
  310. // per pixel, with four color and alpha bytes
  311. // per int value.
  312. int[] oneDPix = new int[imgCols * imgRows * 4];
  313. //Move the data into the 1D array. Note the
  314. // use of the bitwise OR operator and the
  315. // bitwise left-shift operators to put the
  316. // four 8-bit bytes into each int.
  317. for(int row = 0,cnt = 0;row < imgRows;row++){
  318. for(int col = 0;col < imgCols;col++){
  319. oneDPix[cnt] = ((data[row][col][0] << 24) & 0xFF000000) | ((data[row][col][1] << 16)
  320. & 0x00FF0000) | ((data[row][col][2] << 8) & 0x0000FF00)
  321. | ((data[row][col][3]) & 0x000000FF);
  322. cnt++;
  323. }//end for loop on col
  324. }//end for loop on row
  325. return oneDPix;
  326. }//end convertToOneDim
  327. }//end ImgMod3.java class
  328. //=============================================//
Reply With Quote Quick reply to this message  
Join Date: Nov 2006
Posts: 27
Reputation: anti_genius is an unknown quantity at this point 
Solved Threads: 0
anti_genius anti_genius is offline Offline
Light Poster

Re: Adding mouse listener to a frame

 
0
  #9
Nov 24th, 2006
Hi,

I have implemented the MouseListener on Canvas class and it worked that way too. But i still can't understand why is it not working on Frame.

Regards.
Reply With Quote Quick reply to this message  
Join Date: Mar 2004
Posts: 765
Reputation: Phaelax is on a distinguished road 
Solved Threads: 38
Phaelax Phaelax is offline Offline
Master Poster

Re: Adding mouse listener to a frame

 
0
  #10
Nov 25th, 2006
Here's a little example that should demonstrate what is probably going on in your code.
  1. import java.awt.*;
  2. import java.awt.event.*;
  3.  
  4. class ImgMod3 extends Frame implements MouseListener
  5. {
  6. public ImgMod3()
  7. {
  8. this.addMouseListener(this);
  9. //this.add(new Panel());
  10.  
  11. this.addWindowListener(new WindowAdapter()
  12. {
  13. public void windowClosing(WindowEvent e)
  14. {
  15. System.exit(0);
  16. }
  17. });
  18. }
  19.  
  20.  
  21. public void mouseClicked(MouseEvent e)
  22. {
  23. javax.swing.JOptionPane.showMessageDialog(this, "Mouse button clicked");
  24. }
  25.  
  26. public void mouseEntered(MouseEvent e){}
  27.  
  28. public void mouseExited(MouseEvent e){}
  29.  
  30. public void mousePressed(MouseEvent e){}
  31.  
  32. public void mouseReleased(MouseEvent e){}
  33.  
  34. public static void main(String[] args)
  35. {
  36. ImgMod3 frame = new ImgMod3();
  37. frame.pack();
  38. frame.setSize(300,300);
  39. frame.setVisible(true);
  40. }
  41. }

If you uncomment the line in the constructor then run the program, you'll notice that the events are no longer triggered. It's because the Frame is covered up by another component, so technically it'd be like trying to click on a window that's behind another window.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Other Threads in the Java Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC