SlideShare a Scribd company logo
1 of 4
Download to read offline
Modify the following source code so that when the mouse is clicked within 30 pixels of the
middle of the smiley face it changes color. It will alternate between the yellow and red smiley
faces.
two images have been given to you , redSmiley.gif and happyFace.gif to get started.
Just for fun:
Create more than 2 colors of smiley faces and rotate through the images changing each time the
mouse is clicked within the threshold.
Use different images other than smiley faces, change images each time the mouse is clicked
within the threshold.
Add a sound each time the image changes.
Have the image slow down, if it has been more than x number of seconds since the image has
changed.
Solution
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class ChangeImageOnClick {
private void showContentsImage() {
JFrame driver = new JFrame("Move pointer on Image");
driver.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
CustomPanel contentPane = new CustomPanel();
driver.setContentPane(contentPane);
driver.pack();
driver.setLocationByPlatform(true);
driver.setVisible(true);
}
public static void main(Stringu005Bu005D args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ChangeImageOnClick().showContentsImage();
}
});
}
}
class CustomPanel extends JComponent {
private final int SIZE = 50;
private int imageX = 100;
private int imageY = 100;
private int imageIndex;
private ImageIcon image;
private ImageIcon firstImage;
private ImageIcon secondImage;
private java.net.URL url;
private Rectangle boundsForMouse;
public CustomPanel() {
image = new ImageIcon();
try {
url = new java.net.URL("please mention url location of imaage");
firstImage = new ImageIcon(url);
url = new java.net.URL("please mention url location of image");
secondImage = new ImageIcon(url);
} catch(Exception e) {
e.printStackTrace();
}
imageIndex = 1;
image.setImage(firstImage.getImage());
boundsForMouse = new Rectangle(imageX - 30,
imageY - 30,
firstImage.getIconWidth() + 60,
firstImage.getIconHeight() + 60);
setOpaque(true);
addMouseListener(new MousePosition());
}
private int setImage(int counter) {
System.out.println("Image Index : " + counter);
if (counter == 1) {
image = new ImageIcon();
image.setImage(secondImage.getImage());
boundsForMouse = new Rectangle(imageX - 30,
imageY - 30,
secondImage.getIconWidth() + 60,
secondImage.getIconHeight() + 60);
repaint();
counter++;
return (counter);
} else if (counter == 2) {
image = new ImageIcon();
image.setImage(firstImage.getImage());
boundsForMouse = new Rectangle(imageX - 30,
imageY - 30,
firstImage.getIconWidth() + 60,
firstImage.getIconHeight() + 60);
repaint();
return (--counter);
}
return 1;
}
@Override
public Dimension getPreferredSize() {
return (new Dimension(500, 500));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.clearRect(0, 0, getWidth(), getHeight());
g.drawImage(image.getImage(), imageX, imageY, null);
}
private class MousePosition extends MouseAdapter {
public void mouseClicked(MouseEvent me) {
int xHitOnPanel = me.getX();
int yHitOnPanel = me.getY();
System.out.println("Click on x pannel : " + xHitOnPanel);
System.out.println("Click on y pannel : " + yHitOnPanel);
System.out.println("Image X : " + boundsForMouse.x);
System.out.println("Image Y : " + boundsForMouse.y);
if (boundsForMouse.contains(xHitOnPanel, yHitOnPanel))
imageIndex = setImage(imageIndex);
}
}
}

More Related Content

Similar to Modify the following source code so that when the mouse is clicked w.pdf

This is Java,I am currently stumped on how to add a scoreboard for.pdf
This is Java,I am currently stumped on how to add a scoreboard for.pdfThis is Java,I am currently stumped on how to add a scoreboard for.pdf
This is Java,I am currently stumped on how to add a scoreboard for.pdf
anjandavid
 
14multithreaded Graphics
14multithreaded Graphics14multithreaded Graphics
14multithreaded Graphics
Adil Jafri
 
Creating image thumbnails in asp.net
Creating image thumbnails in asp.netCreating image thumbnails in asp.net
Creating image thumbnails in asp.net
gridviewnet
 
Why am I getting an out of memory error and no window of my .pdf
Why am I getting an out of memory error and no window of my .pdfWhy am I getting an out of memory error and no window of my .pdf
Why am I getting an out of memory error and no window of my .pdf
aakarcreations1
 
openFrameworks 007 - graphics
openFrameworks 007 - graphicsopenFrameworks 007 - graphics
openFrameworks 007 - graphics
roxlu
 

Similar to Modify the following source code so that when the mouse is clicked w.pdf (20)

Creating an Uber Clone - Part XXXIX.pdf
Creating an Uber Clone - Part XXXIX.pdfCreating an Uber Clone - Part XXXIX.pdf
Creating an Uber Clone - Part XXXIX.pdf
 
iOS Training Session-3
iOS Training Session-3iOS Training Session-3
iOS Training Session-3
 
Ui perfomance
Ui perfomanceUi perfomance
Ui perfomance
 
662305 LAB13
662305 LAB13662305 LAB13
662305 LAB13
 
Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)Useful Tools for Making Video Games - XNA (2008)
Useful Tools for Making Video Games - XNA (2008)
 
This is Java,I am currently stumped on how to add a scoreboard for.pdf
This is Java,I am currently stumped on how to add a scoreboard for.pdfThis is Java,I am currently stumped on how to add a scoreboard for.pdf
This is Java,I am currently stumped on how to add a scoreboard for.pdf
 
XNA coding series
XNA coding seriesXNA coding series
XNA coding series
 
14multithreaded Graphics
14multithreaded Graphics14multithreaded Graphics
14multithreaded Graphics
 
#JavaFX.forReal()
#JavaFX.forReal()#JavaFX.forReal()
#JavaFX.forReal()
 
How to Animate a Widget Across Screens in Flutter.pptx
How to Animate a Widget Across Screens in Flutter.pptxHow to Animate a Widget Across Screens in Flutter.pptx
How to Animate a Widget Across Screens in Flutter.pptx
 
Creating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdfCreating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdf
 
Leaving Interface Builder Behind
Leaving Interface Builder BehindLeaving Interface Builder Behind
Leaving Interface Builder Behind
 
Макс Грибов — Использование SpriteKit в неигровых приложениях
Макс Грибов — Использование SpriteKit в неигровых приложенияхМакс Грибов — Использование SpriteKit в неигровых приложениях
Макс Грибов — Использование SpriteKit в неигровых приложениях
 
Creating image thumbnails in asp.net
Creating image thumbnails in asp.netCreating image thumbnails in asp.net
Creating image thumbnails in asp.net
 
WaveEngine 2D components
WaveEngine 2D componentsWaveEngine 2D components
WaveEngine 2D components
 
Animations - Part 3.pdf
Animations - Part 3.pdfAnimations - Part 3.pdf
Animations - Part 3.pdf
 
Why am I getting an out of memory error and no window of my .pdf
Why am I getting an out of memory error and no window of my .pdfWhy am I getting an out of memory error and no window of my .pdf
Why am I getting an out of memory error and no window of my .pdf
 
openFrameworks 007 - graphics
openFrameworks 007 - graphicsopenFrameworks 007 - graphics
openFrameworks 007 - graphics
 
Android Oreo
Android OreoAndroid Oreo
Android Oreo
 
Unity3d scripting tutorial
Unity3d scripting tutorialUnity3d scripting tutorial
Unity3d scripting tutorial
 

More from arorastores

Need this in JAVA We have N numbers as an array, you need to find a .pdf
Need this in JAVA We have N numbers as an array, you need to find a .pdfNeed this in JAVA We have N numbers as an array, you need to find a .pdf
Need this in JAVA We have N numbers as an array, you need to find a .pdf
arorastores
 
looking for help with this question, have another question that.pdf
looking for help with this question, have another question that.pdflooking for help with this question, have another question that.pdf
looking for help with this question, have another question that.pdf
arorastores
 
I have a Student.java class constructor like thisAnd I need to re.pdf
I have a Student.java class constructor like thisAnd I need to re.pdfI have a Student.java class constructor like thisAnd I need to re.pdf
I have a Student.java class constructor like thisAnd I need to re.pdf
arorastores
 
How do incomplete dominance and codominance differ There is no diff.pdf
How do incomplete dominance and codominance differ  There is no diff.pdfHow do incomplete dominance and codominance differ  There is no diff.pdf
How do incomplete dominance and codominance differ There is no diff.pdf
arorastores
 
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdfHelp please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
arorastores
 
Describe the transmission of the meningococcus, and discuss the path.pdf
Describe the transmission of the meningococcus, and discuss the path.pdfDescribe the transmission of the meningococcus, and discuss the path.pdf
Describe the transmission of the meningococcus, and discuss the path.pdf
arorastores
 
dass Defining Species art C Gene flow and the biological species conc.pdf
dass Defining Species art C Gene flow and the biological species conc.pdfdass Defining Species art C Gene flow and the biological species conc.pdf
dass Defining Species art C Gene flow and the biological species conc.pdf
arorastores
 
Describe one way in which you could use butterfly rearing in the fut.pdf
Describe one way in which you could use butterfly rearing in the fut.pdfDescribe one way in which you could use butterfly rearing in the fut.pdf
Describe one way in which you could use butterfly rearing in the fut.pdf
arorastores
 
An infinitely long sheet of charge of width L lies in the xy -plane .pdf
An infinitely long sheet of charge of width L lies in the xy -plane .pdfAn infinitely long sheet of charge of width L lies in the xy -plane .pdf
An infinitely long sheet of charge of width L lies in the xy -plane .pdf
arorastores
 
A study tracked incidence rates of a blood vessel disorder over time.pdf
A study tracked incidence rates of a blood vessel disorder over time.pdfA study tracked incidence rates of a blood vessel disorder over time.pdf
A study tracked incidence rates of a blood vessel disorder over time.pdf
arorastores
 

More from arorastores (20)

Need this in JAVA We have N numbers as an array, you need to find a .pdf
Need this in JAVA We have N numbers as an array, you need to find a .pdfNeed this in JAVA We have N numbers as an array, you need to find a .pdf
Need this in JAVA We have N numbers as an array, you need to find a .pdf
 
looking for help with this question, have another question that.pdf
looking for help with this question, have another question that.pdflooking for help with this question, have another question that.pdf
looking for help with this question, have another question that.pdf
 
In a population of Canadian Eskimos the autosomal recessive gene for.pdf
In a population of Canadian Eskimos the autosomal recessive gene for.pdfIn a population of Canadian Eskimos the autosomal recessive gene for.pdf
In a population of Canadian Eskimos the autosomal recessive gene for.pdf
 
How is that terrorists are able to use media to their advantage an.pdf
How is that terrorists are able to use media to their advantage an.pdfHow is that terrorists are able to use media to their advantage an.pdf
How is that terrorists are able to use media to their advantage an.pdf
 
Identify the three ventral body cavities and the two dorsal body cavi.pdf
Identify the three ventral body cavities and the two dorsal body cavi.pdfIdentify the three ventral body cavities and the two dorsal body cavi.pdf
Identify the three ventral body cavities and the two dorsal body cavi.pdf
 
I have a Student.java class constructor like thisAnd I need to re.pdf
I have a Student.java class constructor like thisAnd I need to re.pdfI have a Student.java class constructor like thisAnd I need to re.pdf
I have a Student.java class constructor like thisAnd I need to re.pdf
 
How do incomplete dominance and codominance differ There is no diff.pdf
How do incomplete dominance and codominance differ  There is no diff.pdfHow do incomplete dominance and codominance differ  There is no diff.pdf
How do incomplete dominance and codominance differ There is no diff.pdf
 
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdfHelp please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
 
Fruits develop from microsporangia receptacles fertilized eggs ovarie.pdf
Fruits develop from microsporangia receptacles fertilized eggs ovarie.pdfFruits develop from microsporangia receptacles fertilized eggs ovarie.pdf
Fruits develop from microsporangia receptacles fertilized eggs ovarie.pdf
 
Find all equilibrium solutions of the equation dydx = y^2 - 1. Use o.pdf
Find all equilibrium solutions of the equation dydx = y^2 - 1. Use o.pdfFind all equilibrium solutions of the equation dydx = y^2 - 1. Use o.pdf
Find all equilibrium solutions of the equation dydx = y^2 - 1. Use o.pdf
 
Determine which protist causes each of the following diseases in huma.pdf
Determine which protist causes each of the following diseases in huma.pdfDetermine which protist causes each of the following diseases in huma.pdf
Determine which protist causes each of the following diseases in huma.pdf
 
Describe the transmission of the meningococcus, and discuss the path.pdf
Describe the transmission of the meningococcus, and discuss the path.pdfDescribe the transmission of the meningococcus, and discuss the path.pdf
Describe the transmission of the meningococcus, and discuss the path.pdf
 
dass Defining Species art C Gene flow and the biological species conc.pdf
dass Defining Species art C Gene flow and the biological species conc.pdfdass Defining Species art C Gene flow and the biological species conc.pdf
dass Defining Species art C Gene flow and the biological species conc.pdf
 
Describe one way in which you could use butterfly rearing in the fut.pdf
Describe one way in which you could use butterfly rearing in the fut.pdfDescribe one way in which you could use butterfly rearing in the fut.pdf
Describe one way in which you could use butterfly rearing in the fut.pdf
 
Critical Thinking Course...PhilosophyIn Chapter 8, we learned the .pdf
Critical Thinking Course...PhilosophyIn Chapter 8, we learned the .pdfCritical Thinking Course...PhilosophyIn Chapter 8, we learned the .pdf
Critical Thinking Course...PhilosophyIn Chapter 8, we learned the .pdf
 
Can I get a detailed answer on the following question. Bacterial ind.pdf
Can I get a detailed answer on the following question. Bacterial ind.pdfCan I get a detailed answer on the following question. Bacterial ind.pdf
Can I get a detailed answer on the following question. Bacterial ind.pdf
 
Another algebraic way to express a constraint is E_1 = E_2, where bot.pdf
Another algebraic way to express a constraint is E_1 = E_2, where bot.pdfAnother algebraic way to express a constraint is E_1 = E_2, where bot.pdf
Another algebraic way to express a constraint is E_1 = E_2, where bot.pdf
 
An infinitely long sheet of charge of width L lies in the xy -plane .pdf
An infinitely long sheet of charge of width L lies in the xy -plane .pdfAn infinitely long sheet of charge of width L lies in the xy -plane .pdf
An infinitely long sheet of charge of width L lies in the xy -plane .pdf
 
A study tracked incidence rates of a blood vessel disorder over time.pdf
A study tracked incidence rates of a blood vessel disorder over time.pdfA study tracked incidence rates of a blood vessel disorder over time.pdf
A study tracked incidence rates of a blood vessel disorder over time.pdf
 
A distant galaxy was found to have a redshift of 1.8. How far away i.pdf
A distant galaxy was found to have a redshift of 1.8. How far away i.pdfA distant galaxy was found to have a redshift of 1.8. How far away i.pdf
A distant galaxy was found to have a redshift of 1.8. How far away i.pdf
 

Recently uploaded

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 

Recently uploaded (20)

Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 

Modify the following source code so that when the mouse is clicked w.pdf

  • 1. Modify the following source code so that when the mouse is clicked within 30 pixels of the middle of the smiley face it changes color. It will alternate between the yellow and red smiley faces. two images have been given to you , redSmiley.gif and happyFace.gif to get started. Just for fun: Create more than 2 colors of smiley faces and rotate through the images changing each time the mouse is clicked within the threshold. Use different images other than smiley faces, change images each time the mouse is clicked within the threshold. Add a sound each time the image changes. Have the image slow down, if it has been more than x number of seconds since the image has changed. Solution import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import javax.swing.*; public class ChangeImageOnClick { private void showContentsImage() { JFrame driver = new JFrame("Move pointer on Image"); driver.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); CustomPanel contentPane = new CustomPanel(); driver.setContentPane(contentPane); driver.pack(); driver.setLocationByPlatform(true); driver.setVisible(true); } public static void main(Stringu005Bu005D args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new ChangeImageOnClick().showContentsImage(); }
  • 2. }); } } class CustomPanel extends JComponent { private final int SIZE = 50; private int imageX = 100; private int imageY = 100; private int imageIndex; private ImageIcon image; private ImageIcon firstImage; private ImageIcon secondImage; private java.net.URL url; private Rectangle boundsForMouse; public CustomPanel() { image = new ImageIcon(); try { url = new java.net.URL("please mention url location of imaage"); firstImage = new ImageIcon(url); url = new java.net.URL("please mention url location of image"); secondImage = new ImageIcon(url); } catch(Exception e) { e.printStackTrace(); } imageIndex = 1; image.setImage(firstImage.getImage()); boundsForMouse = new Rectangle(imageX - 30, imageY - 30, firstImage.getIconWidth() + 60, firstImage.getIconHeight() + 60); setOpaque(true); addMouseListener(new MousePosition()); } private int setImage(int counter) { System.out.println("Image Index : " + counter); if (counter == 1) { image = new ImageIcon();
  • 3. image.setImage(secondImage.getImage()); boundsForMouse = new Rectangle(imageX - 30, imageY - 30, secondImage.getIconWidth() + 60, secondImage.getIconHeight() + 60); repaint(); counter++; return (counter); } else if (counter == 2) { image = new ImageIcon(); image.setImage(firstImage.getImage()); boundsForMouse = new Rectangle(imageX - 30, imageY - 30, firstImage.getIconWidth() + 60, firstImage.getIconHeight() + 60); repaint(); return (--counter); } return 1; } @Override public Dimension getPreferredSize() { return (new Dimension(500, 500)); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.clearRect(0, 0, getWidth(), getHeight()); g.drawImage(image.getImage(), imageX, imageY, null); } private class MousePosition extends MouseAdapter { public void mouseClicked(MouseEvent me) { int xHitOnPanel = me.getX(); int yHitOnPanel = me.getY(); System.out.println("Click on x pannel : " + xHitOnPanel); System.out.println("Click on y pannel : " + yHitOnPanel);
  • 4. System.out.println("Image X : " + boundsForMouse.x); System.out.println("Image Y : " + boundsForMouse.y); if (boundsForMouse.contains(xHitOnPanel, yHitOnPanel)) imageIndex = setImage(imageIndex); } } }