Question

*15.7 (Change color using a mouse) Write a program that displays the color of a circle...

*15.7 (Change color using a mouse) Write a program that displays the color of a circle as red when the mouse button is pressed and as blue when the mouse button is released. Please complete using Java language

0 0
Add a comment Improve this question Transcribed image text
Answer #1

ChangeColor.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// implement mouselistener for work with mouse events
public class ChangeColor extends JFrame implements MouseListener
{
boolean flag=false;
public ChangeColor() // constructor
{
setTitle("Change Circle Color On Mouse Action"); // set title to the jframe
setSize(500,500); // set size of the jframe
// when user clicks X button then jframe will be close
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // setting jframe visible
addMouseListener(this); // add mouse listener

}
public void paint(Graphics g)
{
super.paint(g);
if(flag) // if mouse button is pressed then
g.setColor(Color.BLACK);
else // if mouse button is released then
g.setColor(Color.WHITE);
g.fillOval(100,100,300,300); // draws filled oval
}

// overriding all mouse listener methods
@Override
public void mousePressed(MouseEvent e)
{
flag=true;
repaint();
}
@Override
public void mouseReleased(MouseEvent e)
{
flag=false;
repaint();
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
public static void main(String args[])
{
new ChangeColor(); // creating anonymous object of ChangeColor class
}
}

Output

C:\Users\AKSHAY\Desktop>javac ChangeColor.java

C:\Users\AKSHAY\Desktop>java ChangeColor

Mouse Button is Pressed

Mouse Button is Released

Add a comment
Know the answer?
Add Answer to:
*15.7 (Change color using a mouse) Write a program that displays the color of a circle...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT