Drawing lines and deleting lines - java

I am trying to create a program that allows the user to drag and draw lines and also delete the lines after it have been drawn. Is there any ways i can do it? I have the code that draws the line but i am not sure how i could delete the lines after i have drawn it. Im looking to click any of the lines drawn and delete it with the delete button.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Drawing {
public Drawing() {
JFrame jf=new JFrame("Free Hand Drawing Example");
Board draw=new Board();
jf.add(draw);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setSize(600,500);
jf.setVisible(true);
}
public static void main(String a[]){
new Drawing();
}
}
class Board extends JPanel implements MouseListener,MouseMotionListener {
ArrayList<pts> list = new ArrayList<pts>();
Point start,end;
public Board() {
start=null; /*Initializing*/
end=null;
//this.setBackground(Color.BLACK);
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
#Override
public void paint(Graphics g)
{ Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
super.paint(g2);
//g.setColor(Color.BLACK);
for (pts p : list)
g.drawLine((int)p.getStart().getX(), (int)p.getStart().getY(), (int)p.getEnd().getX(), (int)p.getEnd().getY());
if(start!=null)
{
g.drawLine(start.x,start.y,end.x,end.y);
}
}
#Override
public void mouseClicked(MouseEvent arg0) {}
#Override
public void mouseEntered(MouseEvent arg0) {}
#Override
public void mouseExited(MouseEvent arg0) {}
#Override
public void mousePressed(MouseEvent me) {
start = me.getPoint();
}
#Override
public void mouseReleased(MouseEvent me) {
end = me.getPoint();
pts pt = new pts(start,end);
list.add(pt);
repaint();
for(pts p : list)
{
System.out.println(p.getStart()+""+p.getEnd());
}
start = null;
end = null;
}
#Override
public void mouseDragged(MouseEvent me) {
end = me.getPoint();
repaint();
}
#Override
public void mouseMoved(MouseEvent arg0) {}
}
class pts{
Point start = null;
Point end = null;
public pts(Point start, Point end){
this.start = start;
this.end = end;
}
public Point getStart(){
return this.start;
}
public Point getEnd(){
return this.end;
}
}

There is more than one way to go about this, but one simple approach would be to add a 'delete' button with an ActionListener that clears out the list of points you have when the button is pressed. You could also associate the clearing action with something like a MouseDragged event, but that doesn't seem very user friendly.
UPDATE:
So, to delete the line when the user clicks on it, you could use a simple function like this one:
public boolean intersects(Point linePoint1,
Point linePoint2,
Point usersClickPoint) {
return new Line2D.Float(linePoint1, linePoint2).
ptLineDist(usersClickPoint) <= 0.01;//some margin of error
}
in your MousePressed method.
Side Note: The way you've chosen to interpret the mouse events is a bit strange. You record the first point on MousePressed, and the second one on MouseReleased. Why not use MouseClicked and simply keep track of the first and second clicks when drawing the line?

One approach would be to create a Line object for each line your user draws and have the object store the locations on the screen where the line is drawn. Then when in delete mode, have an onClickListener that will select a line based upon the coordinates of the click matching up to a point contained in a line. Then just delete the line (probably could redraw using the same endpoints but with the pen set to the background color). There would need to be some logic for the possible case where lines intersect and you don't want to delete a portion of the other line, but that could be solved fairly easily. Keep in mind, I'm not a big graphics programmer. This is just my idea.

Related

Gui- make an object move by a certain criteria

I am trying to make a particular "Pacman Game".
Basically the main objects are: pacman and fruit.
The background image is a picture of a certain map, meaning the game is bound by an exterior frame.
The frame itself is set in pixels which I convert to coordinates (Conversion of lat/lng coordinates to pixels on a given map (with JavaScript)).
coordinates have the following parameters:
public Point3D(double x,double y,double z)
{
_x=x;// latitude
_y=y;// longtitude
_z=z;// altitude
}
public boolean isValid_GPS_Point(Point3D p)
{
return (p.x()<=180&&p.x()>=-180&&p.y()<=90&&p.y()>=-90&&p.z()>=-450);
}
Fruits are static objects that do not move.
All pacmen have a universal speed of 1 meter per second and an eating radius of 1 meter, meaning every fruit in the eating radius of the particular pacman will be eaten and removed from fruit list(The 'Eating Radius' is more like a third dimensional sphere having a 1 meter radius).
Pacmen movement is determined by an algorithm (Algorithm: using a list of fruits and pacmen, we calculate the distance of 2 objects from both lists, taking the minimal distance needed for a specific pacman to travel.
Distance Formula:
Determining the vector by 2 GPS points on map.
Using square function on the vector: sqrt(delta(x)^2+delta(y)^2+delta(z)^2)
In terms of Gui:
package gui;
import java.awt.Graphics;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class MainWindow extends JFrame implements MouseListener
{
public BufferedImage myImage;
public MainWindow()
{
initGUI();
this.addMouseListener(this);
}
private void initGUI()
{
MenuBar menuBar = new MenuBar();
Menu File = new Menu("File");
Menu Run=new Menu("Run");
Menu Insert=new Menu("Insert");
MenuItem New=new MenuItem("New");
MenuItem Open = new MenuItem("Open");
MenuItem Save=new MenuItem("Save");
MenuItem start=new MenuItem("start");
MenuItem stop=new MenuItem("stop");
MenuItem packman=new MenuItem("packman");
MenuItem fruit=new MenuItem("fruit");
menuBar.add(File);
menuBar.add(Run);
menuBar.add(Insert);
File.add(New);
File.add(Open);
File.add(Save);
Run.add(start);
Run.add(stop);
Insert.add(packman);
Insert.add(fruit);
this.setMenuBar(menuBar);
try {
myImage = ImageIO.read(new File("C:\\Users\\Owner\\Desktop\\Matala3\\Ariel1.png"));//change according to your path
} catch (IOException e) {
e.printStackTrace();
}
}
int x = -1;
int y = -1;
public void paint(Graphics g)
{
g.drawImage(myImage, 0, 0, this);
if(x!=-1 && y!=-1)
{
int r = 10;
x = x - (r / 2);
y = y - (r / 2);
g.fillOval(x, y, r, r);
}
}
#Override
public void mouseClicked(MouseEvent arg) {
System.out.println("mouse Clicked");
System.out.println("("+ arg.getX() + "," + arg.getY() +")");
x = arg.getX();
y = arg.getY();
repaint();
}
#Override
public void mouseEntered(MouseEvent arg0) {
System.out.println("mouse entered");
}
#Override
public void mouseExited(MouseEvent arg0) {
System.out.println("mouse exited");
}
#Override
public void mousePressed(MouseEvent arg0) {
System.out.println("mouse Click pressed");
}
#Override
public void mouseReleased(MouseEvent arg0) {
System.out.println("mouse Click released");
}
}
Running it from this class:
package gui;
import javax.swing.JFrame;
import Geom.Point3D;
import gis.Fruit;
public class Main
{
public static void main(String[] args)
{
MainWindow window = new MainWindow();
window.setVisible(true);
window.setSize(window.myImage.getWidth(),window.myImage.getHeight());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
My main goal is after that after I place my objects(pacmens and fruits) on the map it should somehow look like this: https://media.giphy.com/media/5UDHI0JLxBBElUFuCs/giphy.gif
I'm looking for a general direction for how to make my packmen move like this and not stay stationary.
You want to make so that the pac men (?) will chase the fruits in a straight line, right?
This is really simple and it should look hilarious if you add more and more features.
You would make a loop trying to find the closest fruit and then make a line using two points: the position of the pacman and the fruit. You then need to subtract the point of the fruit minus the pacman. This is the vector that represents the line the pacman will need to go. Normalize the vector to get a unit-length vector that we can work with. Now, we need to add a tiny fraction of this vector to move the pacman to the fruit. The formula is "
vector * speed * time_delta
", where time_delta is 1 divided by the fps or the actual time difference if you can get it. I normally use the first. This is so in one second, you pacman will have moved at the specified speed. (Keep in mind you specify how many meters a pixel is!)
// calculate line
Vector a = packman.getPosition();
Vector b = fruit.getPosition();
Vector ab = b.subtract(a).normalize();
// for each tick!
packman.addPosition(ab.multiply(speed * 1 / fps));
Reference:
For the eating part you only delete fruits from a list if they are close enough from the pacman. To add fruits you can do the same, add them to a list. You can also make the pacman store the fruit object to simulate a "target lock" or constantly check for the closest fruit.
Hope this has helped you and I would love to see your game!

Java painting program giving many errors

I want to make a simple painting program. So,when you drag your mouse a line will draw in a GUI. The problem is when the user drags the mouse, it will paint automatically, but my code doesn't work. Can someone please tell me how do this? Sorry for my English and if you don't understand my question, look at my code maybe you will than.
My main class:
import javax.swing.JFrame;
public class MainClass {
public static void main(String args[]){
tuna kip = new tuna();
kip.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
kip.setSize(800,600);
kip.setVisible(true);
}
}
This is my other class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class tuna extends JFrame {
JPanel jpanel = new JPanel();
public tuna(){
super("Painting Program");
jpanel.setBackground(Color.WHITE);
add(jpanel);
hand handler = new hand();
jpanel.addMouseListener(handler);
jpanel.addMouseMotionListener(handler);
}
private class hand implements MouseListener ,MouseMotionListener { //THE ERRORS START TO APPEAR HERE
public void mouseDragged(MouseEvent event){
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(event.getX(), event.getY(), 5, 5);
}
}
}
}
When I try to run the code I get too much error messages:
You mean when you try to compile the code you get compile errors.
class hand implements MouseListener ,MouseMotionListener
Your class does not implement all the methods in those listeners. You only implement one method.
Read the section from the Swing tutorial on How to Write a MouseMotionListener for a working example.
If you only care about the mouseDragged() method then you only need to implement the MouseMotionListener.
Or as a simpler solution you can extend MouseMotionAdapter. This class implements all the methods of the MouseMotionListener so you only need to override the methods you want to change. The tutorial also discusses adapters.
Finally class names SHOULD start with an upper case character. Look at the Java API and you will notice this. Follow the Java conventions and don't make up your own.
Yes, there are so many issues in your codes. I just edited it and make it runnable at least. Just study and experiment on it. I hope you will learn something out of this even if I don't explain all of the changes.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class tuna extends JFrame {
int x, y, w, h;
MyPanel jpanel = new MyPanel();
public tuna(){
super("Painting Program");
setLayout(new BorderLayout());
jpanel.setBackground(Color.WHITE);
add(jpanel);
hand handler = new hand();
jpanel.addMouseListener(handler);
jpanel.addMouseMotionListener(handler);
}
private class hand implements MouseListener , MouseMotionListener { //THE ERRORS START TO APPEAR HERE
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
x=e.getX();
y=e.getY();
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
w = e.getX() - x;
h = e.getY() - y;
jpanel.repaint();
}
public void mouseMoved(MouseEvent e) {
}
}
class MyPanel extends JPanel {
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(x, y, w, h);
}
}
}

Displaying characters typed at mouse location in Java GUI

I have a Java exercise using KeyListeners that I have been stuck on for a while. Any help would be greatly appreciated. The exercise is:
"Write a program to get a character input from the keyboard and display the character where the mouse points."
I did some debugging and it seems like the KeyListener is never registering when a key is pressed.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class EventProgrammingExercise10 extends JFrame {
CharPanel chars;
private int x;
private int y;
String s;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
EventProgrammingExercise10 frame = new EventProgrammingExercise10();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public EventProgrammingExercise10() {
setTitle("EventProgrammingExercise10");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
chars = new CharPanel();
chars.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
chars.repaint();
}
});
add(chars);
}
public void setX(int n) {
x = n;
}
public void setY(int n) {
y = n;
}
class MouseLocListener extends MouseMotionAdapter {
public void mouseMoved(MouseEvent e) {
setX(e.getX());
setY(e.getY());
}
}
class CharPanel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(String.valueOf('a'), x, y);
}
}
}
Thanks.
A KeyListener will only work if the component that owns it has the focus. You must first make your JPanel focusable, i.e., setFocusable(true), and then request that it have focus, i.e., requestFocusInWindow().
I wouldn't use a MouseListener at all. What I'd do if I had to use a KeyListener, and what I know works, would be:
Make my JPanel Focusable and have focus
Give it a BufferedImage that is exactly its size and draw this in its paintComponent method.
Add a KeyListener/KeyAdapter to it
In the KeyAdapter, keyPressed method, Use the MouseInfo class to get a PointerInfo object: PointerInfo pInfo = MouseInfo.getPointInfo()
Use PointerInfo to get the current mouse's location on screen via pInfo.getLocation();
Get the drawing JPanel's locationOnScreen.
Translate the mouse pointer location to one that is relative to that of the component's using simple vector graphics.
If the point is in bounds of the location, get a Graphics object from the BufferedImage
Draw the char in the BufferedImage
Repaint the JPanel
Look #Hovercraft and you forget to add the MouseLocListener. Than it works :)
chars.addMouseMotionListener(new MouseLocListener());
chars.setFocusable(true);
chars.requestFocusInWindow();
It looks like you should attach lKeyListener not to chars panel but to the frame itself.
This way KeyListener will allways work even if panel losses focus for any reason.

Mouse Listener Interface and painting

I am trying to implement a graphics modelling tool.
On a mouse click a red vertex is generated. When mouse is dragged from one vertex to another, a line should be drawn. This is what I would like to achieve. But my code does not effectively do it. Following is my code and problem
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class NewClass extends JPanel {
Point source,dest;
BufferedImage image;
Graphics2D imageGraphics;
NewClass(){
image= new BufferedImage(400,400, BufferedImage.TYPE_INT_ARGB);
imageGraphics=image.createGraphics();
this.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
if(e.getButton() == MouseEvent.BUTTON1){
Point p=e.getPoint();
paintPoint(p);
}
}
#Override
public void mousePressed(MouseEvent e){
if(e.getButton() == MouseEvent.BUTTON1){
source=e.getPoint();
}
}
#Override
public void mouseReleased(MouseEvent e){
if(e.getButton() == MouseEvent.BUTTON1){
dest=e.getPoint();
paintLine();
}
}
});
}
public void paintPoint(Point r){
imageGraphics.setColor(Color.red);
imageGraphics.fillOval(r.x,r.y,5,5);
repaint();
}
public void paintLine(){
imageGraphics.setColor(Color.black);
imageGraphics.drawLine(source.x,source.y,dest.x,dest.y);
repaint();
}
}
However the problem I am facing is, when a mouseClickedEvent is generated, it generates pressed and released as well. Especially when more than three vertices are used, wrong lines are generated.
I want the line to be drawn only when pressed on a vertex, moved to the next vertex and then released there.
How can this problem be solved?
In the mouseReleased check the location of the release, if it is the same as your source you have a click not a drag. You can also get rid of the mouseClicked completely using this method
You can simply override mouseDragged(MouseEvent e), it's made for your usage.

Expanding on Java Swing/AWT Program

I've written a small Swing program that draws a head and when a JCheckBox instance is selected/unselected by the user a hat is drawn or removed from on top of the head. I'm having some trouble taking the next step with this program -- I'd like to add a boolean field to the Head class that causes this component to listen to mouse events with a MouseListener. From there, I'd like to use two methods to set this field to true/false and render the remaining three methods lame ducks. Also, how would I change the paintComponent method so that if the boolean value is true the object is drawn with open eyes, and if it's false, the head is drawn with the eyes closed? Please provide any advice you have. Many thanks!
import javax.swing.*;
import java.awt.geom.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class Head extends JPanel {
Rectangle2D.Double chapeau, chapeau2;
Ellipse2D.Double bouche, visage, oeil1, oeil2;
JCheckBox box;
public Head(){
this.setBackground(Color.WHITE);
visage = new Ellipse2D.Double (150,130,100,100);
bouche = new Ellipse2D.Double (170,180,60,27);
chapeau = new Rectangle2D.Double (170,80,60,40);
chapeau2 = new Rectangle2D.Double (125,120,150,10);
oeil1 = new Ellipse2D.Double (170,150,20,20);
oeil2 = new Ellipse2D.Double (210,150,20,20);
box = new JCheckBox("Hat");
this.add(box);
box.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
repaint();
}
});
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(3.0f));
g2.setPaint(Color.BLUE);
g2.draw(visage);
g2.draw(oeil1);
g2.draw(oeil2);
g2.draw(bouche);
if(box.isSelected()){
g2.draw(chapeau);
g2.draw(chapeau2);
}
}
public static void main(String[] args){
JFrame f = new JFrame("Face Display Window");
f.setSize(425,285);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setVisible(true);
f.add(new Head());
}
}
----------------------------------- Second Try
import javax.swing.*;
import java.awt.geom.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class Head extends JPanel implements MouseListener {
Rectangle2D.Double chapeau, chapeau2;
Ellipse2D.Double bouche, visage, oeil1, oeil2, oeil3, oeil4;
JCheckBox box;
boolean isClosed = false;
public Head(){
this.setBackground(Color.WHITE);
visage = new Ellipse2D.Double (150,130,100,100);
bouche = new Ellipse2D.Double (170,180,60,27);
chapeau = new Rectangle2D.Double (170,80,60,40);
chapeau2 = new Rectangle2D.Double (125,120,150,10);
oeil1 = new Ellipse2D.Double (170,150,20,20);
oeil2 = new Ellipse2D.Double (210,150,20,20);
oeil3 = new Ellipse2D.Double (175,155,25,25);
oeil4 = new Ellipse2D.Double (215,155,25,25);
box = new JCheckBox("Hat");
this.addMouseListener(this);
this.add(box);
box.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
repaint();
}
});
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(3.0f));
g2.setPaint(Color.BLUE);
g2.draw(visage);
g2.draw(oeil1);
g2.draw(oeil2);
g2.draw(bouche);
if(box.isSelected()){
g2.draw(chapeau);
g2.draw(chapeau2);
if(isClosed) {
g2.draw(oeil3);
g2.draw(oeil4);
}
else {
g2.draw(oeil1);
g2.draw(oeil2);
}
}
}
#Override
public void mouseClicked(MouseEvent e) {
isClosed = !isClosed;
repaint();
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
public static void main(String[] args){
JFrame f = new JFrame("Face Display Window");
f.setSize(425,285);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setVisible(true);
f.add(new Head());
}
}
I'm intentionally being a little vague here because I'm not sure if this is homework or not since you already have a fair amount of code that does a lot of stuff that is very similar to what you want it to and modifying it shouldn't be very difficult. However, if you're actually stuck, please clarify and I'll add more details if required.
I'd like to add a boolean field to the Head class that causes this component to listen to mouse events with a MouseListener.
This isn't too hard, let's walk through it. It's trivial to add a boolean field to your Head class - you simply declare boolean isClosed = false; - indicating that you begin the execution with the field set to false which your code will later interpret as the instruction to draw eyes open.
Your core requirement is the MouseListener. If you haven't already, check out the Java Trail for events; it explains how to implement a simple MouseListener. At this point, note that MouseListener is an interface and thus, you'd necessarily need to provide an implementation for all it's methods, even if they're empty-bodied methods. You may want to check out the MouseAdapter abstract class. It provides empty implementations of all these methods (and more) so that you only need to override the ones you need - this makes your code cleaner since you don't have a bunch of empty methods just to satisfy the compiler. This would solve the problem I believe you're referring to when you say 'and render the remaining three methods lame ducks' Of course, since you're already extending JPanel, you can't extend MouseAdapter as well so this doesn't apply here. But this (with other Adapters) is a useful class to keep in mind for later.
From there, I'd like to use two methods to set this field to true/false
If I understand you correctly, what you want is to toggle the value of isClosed on mouse clicks. So right now, you have a MouseListener/ MouseAdapter that doesn't really do anything. What you need to do next is provide an implementation for, lets say, the MouseClicked() method where you toggle the value of your boolean field. This is really easy as well - you simply invert the current value using the ! (NOT) operator and assign it back the variable - isClosed = !isClosed;. You may wish to read up on operators in Java in more detail.
Also, how would I change the paintComponent method so that if the boolean value is true the object is drawn with open eyes, and if it's false, the head is drawn with the eyes closed?
One way of doing this is to create two more shapes for the two closed eyes, similar to the ones you have for open eyes. Once you've done that, it's a simple matter of deciding which ones to draw (i.e. the closed eyes or the open ones) on the basis of the value of isClosed. So you'd use an if clause to check the value of isClosed and draw the open eyes when it's false and the closed eyes when true. Note that since your value of isClosed is being modified in your click handler, you need to make sure that you call repaint() when you change the value otherwise Swing may not update the panel immediately to show the change so then you won't see anything happen.
To sum it up, one way to do what you want is to make the following modifications to Head:
public class Head
extends JPanel
implements MouseListener {
//...all your other declarations still go here
boolean isClosed = false;
//also declare new 'eyes' which are closed
public Head() {
//..all your existing code is still here
//add code to instantiate closed eyes
//need to register a new MouseListener
//since head itself is a MouseListener, we can pass this as the argument
this.addMouseListener(this);
}
//...all your existing code still goes here
public void paintComponent(Graphics g) {
//...all your existing code still goes here
//decide which eyes to draw depending on isClosed
if(isClosed) {
//draw closed eyes
}
else {
//draw open eyes
}
//draw everything else as before
}
//implementation for MouseListener
//don't forget the rest of the MouseListener events
//mousePressed, mouseReleased, mouseEntered, mouseExited
public void mouseClicked(MouseEvent e) {
//toggle the value of isClosed
isClosed = !isClosed;
//must repaint
repaint();
}

Categories

Resources