beck
beck

Reputation: 3027

AWT Frame does not handle events

The frame opens and close normally but mouse click doesn't work.

import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

//Create a frame window that responds to mouse click
public class AWT3 extends Frame {
    String Mmsg="";
    int mouseX=0, mouseY=0;

    public AWT3() {
        addWindowListener(new MyWindowwAdapter(this));
        addMouseListener(new MyMouseeAdapter(this));
    }

public void paint(Graphics g){
        g.drawString(Mmsg, mouseX, mouseY);
    }

public static void main(String args[]){
    AWT3 awt3 = new AWT3();
    awt3.setSize(new dimension(500, 500));
    awt3.setTitle("Window framee");
    awt3.setVisible(true);
    }
}


class MyWindowwAdapter extends WindowAdapter{
    AWT3 awt3;
    public MyWindowwAdapter(AWT3 awt3) {
        this.awt3=awt3;
    }
    public void windowClosing(WindowEvent we){
        awt3.setVisible(false);
    }
}

class MyMouseeAdapter extends MouseAdapter{
AWT3 awt3;
public MyMouseeAdapter(AWT3 awt3) {
    this.awt3=awt3;
}
public void MouseClicked(MouseEvent me){
    awt3.Mmsg="the mouse is clicked";
    awt3.mouseX= me.getX();
    awt3.mouseY=me.getY();``
    awt3.repaint();
}
}

Upvotes: 2

Views: 90

Answers (3)

ares
ares

Reputation: 4413

From what it looks like, this code won't compile. You have an error that you need to fix:

awt3.setSize(new dimension(500, 500));

to

awt3.setSize(new Dimension(500, 500));

and add the proper import java.awt.Dimension as pointed out by others.

Another mistake is that MouseClicked(MouseEvent me) is not overriding the super class method from MouseAdapter as its syntactically wrong (super class method starts with small case). Change it to mouseClicked(MouseEvent me) (add the optional @Override annotation if you wish).

Upvotes: 2

IUW
IUW

Reputation: 441

mouseClicked() is when the mouse button has been pressed and released.

mousePressed() is when the mouse button has been pressed.

Your code is working. tested on java 1.7. only the problem I saw, was with out importing the java.awt.Dimension class you are trying to create a new dimension(500, 500); although the class name is in simple form you can fix this error and try the code.

Upvotes: 0

shruti1810
shruti1810

Reputation: 4047

The method name should be public void mouseClicked(MouseEvent me) instead of public void MouseClicked(MouseEvent me).

Upvotes: 0

Related Questions