1

Here,is something I wanted to show for the use of MouseEvents of one class in another ...by creating an object of the former class...

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.lang.*;
public class MyPagalpanti extends JPanel implements MouseListener
{Point a,b;
boolean drawLin,drawOvl,drawOvl2;
MyPagalpanti(){a=new Point(0,0);b=new Point(0,0);drawLin=false;drawOvl=false,drawOvl2=false;;setSize(300,300);addMouseListener(this);}
public void mouseClicked(MouseEvent m)
{if(!drawOvl){a=new Point(m.getX(),m.getY());drawOvl=true;drawOvl2=false;}
else {b=new Point(m.getX(),m.getY());drawOvl=true;drawOvl2=true;repaint();}//record("clicked",m);}
}
public void mouseEntered(MouseEvent m)
{
}
public void mousePressed(MouseEvent m)
{a=new Point(m.getX(),m.getY());repaint();}
public void mouseReleased(MouseEvent m)
{b=new Point(m.getX(),m.getY());}
public void mouseExited(MouseEvent m)
{}
public void paintComponent(Graphics g)
{if(drawLin){g.setColor(Color.yellow);g.drawLine((int)a.getX(),(int)a.getY(),(int)b.getX(),(int)b.getY());}//d=0;}
else if(drawOvl&&drawOvl2){g.setColor(Color.red);int width=(int)Math.abs(b.getX()-a.getX());
int h=(int)Math.abs(b.getY()-a.getY());
g.drawOval((int)a.getX(),(int)a.getY(),width,h);
}}
}

the class in which an object of MyPagalpanti is formed:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
//import java.swing.JPanel.*;

public class Mithu extends JFrame// implements MouseListener
{JTextArea jta1,jta2;
Mithu(String title)
{
super(title);
MyPagalpanti p1=new MyPagalpanti();
jta1=new JTextArea();
jta2=new JTextArea();
p1.setOpaque(true);
jta1.setEditable(false);
jta2.setEditable(false);
setForeground(Color.blue);
p1.setPreferredSize(new Dimension(600,600));
p1.setLayout(new GridLayout(3,1,0,0));
getContentPane().add(p1);
pack();
setVisible(true);
}
void record(String s,MouseEvent e)
{jta1.setText(jta1.getText()+"\n"+s+""+e.toString());}
public void mouseClicked(MouseEvent m)
{record("clicked",m);}
public void mouseEntered(MouseEvent m)
{record("entered",m);}
public void mousePressed(MouseEvent m)
{record("pressed",m);}
public void mouseReleased(MouseEvent m)
{ record("released",m);}
public void mouseExited(MouseEvent m)
{record("exited",m);}

public static void main(String args[])
{Mithu m=new Mithu("HI ! Karamvir");
m.setVisible(true);}
}

please don't go word by word...I know my code has many other bugs...coz I am still working on it...but for those who have say that "the MouseEvents will only be delivered to the MouseListener from the component it registered to " ,I guess you are talking correctly but if we see closely, I have used this concept only...in this code..

  • You didn't test this very well. A `MouseListener` is never added to `MouseEvtEx2`, therefore `record` is never called – MadProgrammer Jul 02 '14 at 07:00
  • Use a consistent and logical indent for code blocks. The indentation of the code is intended to help people understand the program flow. – Andrew Thompson Jul 02 '14 at 07:01
  • yyea..but I have imported it from MyPanel class ! I have added MouseListener there. – Karamvir Kaur Jul 02 '14 at 07:02
  • The fact that your neighbor earns a lot of money is irrelevant when you want to buy a house. The fact that the `MyPanel` class implements MouseListener won't magically cause the mouseClicked method in `MouseEvtEx2` to be called: they are two different objects. – JB Nizet Jul 02 '14 at 07:05
  • Of course, but I have created an object of MyPanel class in MouseEvtEx2 ! So, the method should get imported . They are in the same package . So, I have directly created an object of MyPanel in MouseEvtEx2 – Karamvir Kaur Jul 02 '14 at 07:11
  • Methods are not imported. That means nothing. And packages are irrelevant to this question. Java objects are like real object. The fact that your cat and your dog are in the same house doesn't make your cat a dog, and vice-versa. I think you should read an introductory tutorial about objects. – JB Nizet Jul 02 '14 at 07:15

3 Answers3

4

To add it JBNizet's answer...

MouseListeners will only be delivered to components that are displayable and have registered for notification. Creating a component that is listening for mouse events and adding it you component won't magically make those events delivered to your component.

Then, in top of that, you are adding two components to the default (CENTER) position of a component managed by BorderLayout...

getContentPane().add(panelTop);
//...
getContentPane().add(p1);

This effectively makes the first component invisible, meaning it's not displayable...

  • You shouldn't be calling show as it's deprecated, use setVisible instead.
  • You should be calling super.paintComponent in your paintComponent method before doing any custom painting, otherwise you'll end up with no end of painting problems
  • There is no need for paintComponent to be public as you never want anybody to be able to call it directly...

Updated

Unless you register interest in been notified about events, you will never receive notification, regardless of what objects you create or interfaces you implement.

It's like saying "I'm interested in this movie", but unless you go to the cinemas, you'll never see it...

In order for your Mithu class to receive mouse event notification, it must register a MouseListener against the component that it's interested in monitoring.

The following example registers a a MouseListener in the Mithu class against the instance of MyPagalpanti, which allows it to receive mouse events that are generated by the instance of MyPagalpanti

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestMouseListener {

    public static void main(String[] args) {
        new TestMouseListener();
    }

    public TestMouseListener() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                Mithu m = new Mithu("HI ! Karamvir");
                m.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                m.pack();
                m.setLocationRelativeTo(null);
                m.setVisible(true);
            }
        });
    }

    public class Mithu extends JFrame implements MouseListener
    {

        JTextArea jta1;

        Mithu(String title) {
            super(title);
            MyPagalpanti p1 = new MyPagalpanti();
            p1.addMouseListener(this);
            jta1 = new JTextArea();
            p1.setOpaque(true);
            jta1.setEditable(false);
            setForeground(Color.blue);
            setLayout(new GridLayout(2, 1));
            getContentPane().add(jta1);
            getContentPane().add(p1);
            pack();
            setVisible(true);
        }

        void record(String s, MouseEvent e) {
            jta1.append("\n" + s + "" + e.toString());
        }

        public void mouseClicked(MouseEvent m) {
            record("clicked", m);
        }

        public void mouseEntered(MouseEvent m) {
            record("entered", m);
        }

        public void mousePressed(MouseEvent m) {
            record("pressed", m);
        }

        public void mouseReleased(MouseEvent m) {
            record("released", m);
        }

        public void mouseExited(MouseEvent m) {
            record("exited", m);
        }
    }

    public class MyPagalpanti extends JPanel implements MouseListener {

        Point a, b;
        boolean drawLin, drawOvl, drawOvl2;

        MyPagalpanti() {
            a = new Point(0, 0);
            b = new Point(0, 0);
            drawLin = false;
            drawOvl = false;
            drawOvl2 = false;
            setSize(300, 300);
            addMouseListener(this);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

        public void mouseClicked(MouseEvent m) {
            if (!drawOvl) {
                a = new Point(m.getX(), m.getY());
                drawOvl = true;
                drawOvl2 = false;
            } else {
                b = new Point(m.getX(), m.getY());
                drawOvl = true;
                drawOvl2 = true;
                repaint();
            }//record("clicked",m);}
        }

        public void mouseEntered(MouseEvent m) {
        }

        public void mousePressed(MouseEvent m) {
            a = new Point(m.getX(), m.getY());
            repaint();
        }

        public void mouseReleased(MouseEvent m) {
            b = new Point(m.getX(), m.getY());
        }

        public void mouseExited(MouseEvent m) {
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.RED);
            FontMetrics fm = g.getFontMetrics();
            if (a != null && b != null) {
                g.drawString(a + "-" + b, 0, fm.getHeight());
            }
            if (drawLin) {
                g.setColor(Color.yellow);
                g.drawLine((int) a.getX(), (int) a.getY(), (int) b.getX(), (int) b.getY());
            }//d=0;}
            else if (drawOvl && drawOvl2) {
                g.setColor(Color.red);
                int width = (int) Math.abs(b.getX() - a.getX());
                int h = (int) Math.abs(b.getY() - a.getY());
                g.drawOval((int) a.getX(), (int) a.getY(), width, h);
            }
        }
    }

}

Before you go to much further, you really should read through...

As you are going to have some very nasty suprises if you keep following your current approach.

Also, it wouldn't hurt to read through How to Write a Mouse Listener

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • yup! its true that I was adding two components with same layout ..that's really silly to do ! :( But being a beginner, I should make such mistakes so that I can learn :) thanks for guidance ! – Karamvir Kaur Jul 02 '14 at 09:01
  • so, you are saying that we cannot use the methods from a JPanel extended class ..in a JFrame extended class? and also..do you wanna say that mouselistener has to be implemented in both of my classes..and ,I was told that paintComponent method is in JPanel which is a container of light-weight and in order to convert it into heavy weight we put it in JFrame which is a heavy-weight container by initialising an object of type MyPanel in JFrame extended class(in which mouselistener is not immpemented)... – Karamvir Kaur Jul 02 '14 at 11:10
  • 1- Yes, you must register a `MouseListener` against each component you want to monitor mouse events for. 2- A lightweight component is any component that does not have it's own native peer and shares another heavyweight components native peer instead. This means, you can't make a lightweight component into a heavy one, the concept just doesn't works. 3- In order for a component to painted, it must be visible and added to a container which is displayed (visible on the screen) directly or in-directly – MadProgrammer Jul 02 '14 at 11:45
  • Ummm...see,without using MouseListener in one class and making use of an object of another class wich has a MouseListener ,in this (without MouseListener )class,i can use the mouse events...And I have a code demonstrating it... If you think that I am still wrong, I can show you that code... I have got it from someone now ! – Karamvir Kaur Jul 02 '14 at 14:30
  • Understand, the MouseEvents will only be delivered to the MouseListener from the component it registered to and a MouseEvents are contextual, that is, the MouseEvent delivered to your listener are within the context of the component that registered them (specifically, the location) – MadProgrammer Jul 02 '14 at 20:25
  • okay...sir,it's my humble request.. please don't call me mad this time since I am still arguing over this logic...I am just not getting it...see, what I am trying to say is that I have made an object of type MyPanel (which extends JPanel) in MouseEvtEx class ..right? Ok..wait.. lemme send you one filtered code.. – Karamvir Kaur Jul 02 '14 at 21:25
  • Sir,if you ever get time ,please go through my question (not in comments,but the question window ) again...and then give me your reply in these comments... I have edited it and wrote a code of what I wanna say...And I think it is implementing your ideology only but by creating an object (against which you are standing) ...Sorry for giving so much trouble. Thanks in advance.. :) – Karamvir Kaur Jul 02 '14 at 22:08
  • phew! thanks a lot ! I'll surely work all this out...To be frank I noticed many things which I have never even heard of....I need to take in allthese and go through the topic again ! Seriously, thanks for your co-operation,sir ! – Karamvir Kaur Jul 02 '14 at 22:45
3

Your class has mouseClicked(), mouseReleased() etc. methods, but it doesn't implement MouseListener. And even if it was, it's never added as a MouseListener to any component.

So, make your class implement MouseListener:

public class MouseEvtEx2 extends JFrame implements MouseListener {

and add itself as mouse listener to the component you want to listen to:

panelTop.addMouseListener(this);

And of course, to help yourself read and understand your own code, indent it properly.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Add `super.paintComponent` and the fact that the `paintComponent` is `public` and round out the answer ;) – MadProgrammer Jul 02 '14 at 07:02
  • I've added an additional answer which highlights some additional problems. If you want to incorporate it into your answer, I will delete mine and reduce the clutter... – MadProgrammer Jul 02 '14 at 07:08
  • so, you are saying that we cannot use the methods from a JPanel extended class ..in a JFrame extended class? and also..do you wanna say that mouselistener has to be implemented in both of my classes..and ,I was told that paintComponent method is in JPanel which is a container of light-weight and in order to convert it into heavy weight we put it in JFrame which is a heavy-weight container by initialising an object of type MyPanel in JFrame extended class(in which mouselistener is not immpemented)... – Karamvir Kaur Jul 02 '14 at 11:03
2

I made couple of changes to make it work. you need to implement MouseListener on your MouseEvtEx2 Frame and also you need to add it as the MouseListener to your panel p1

public class MouseEvtEx2 extends JFrame implements MouseListener {
    private JTextArea txtArea;

    public MouseEvtEx2(String title) {
        super(title);
        Panel p1 = new Panel();
        MyPanel panelTop = new MyPanel();
        panelTop.setBackground(new Color(0.98f, 0.97f, 0.85f));
        panelTop.setOpaque(true);
        panelTop.setPreferredSize(new Dimension(400, 200));
        panelTop.setBorder(BorderFactory.createRaisedBevelBorder());

        getContentPane().add(panelTop);
        txtArea = new JTextArea();
        txtArea.setEditable(false);
        JScrollPane pane = new JScrollPane(txtArea);
        pane.setPreferredSize(new Dimension(400, 200));
        p1.setLayout(new GridLayout(2, 1, 0, 0));
        getContentPane().add(p1);
        p1.addMouseListener(this);
        p1.add(pane);

        // txtArea.setText
        // revalidate();
        setSize(600, 600);
        show();
    }

    public void record(String st, MouseEvent et) {
        txtArea.setText("" + st + "" + et.toString());
    }// setVisible(true);}

    public void mouseClicked(MouseEvent evt) {
        record("Mouse clicked # of mouse clicks: " + evt.getClickCount(), evt);// +
                                                                                // " "
                                                                                // +

    }

    public void mouseEntered(MouseEvent evt) {
        record("Mouse entered ", evt);// .toString());
    }

    public void mouseExited(MouseEvent evt) {
        record("Mouse exited ", evt);// .toString());
    }

    public void mousePressed(MouseEvent evt) {
        record("Mouse pressed # of mouse clicks: ", evt);// .getClickCount() +
                                                            // " " +

    }

    public void mouseReleased(MouseEvent evt) {
        record("Mouse released ", evt);
    }

    public static void main(String[] args) {
        new MouseEvtEx2("Mouse events");
    }
}

Hope this helps.

Sanjeev
  • 9,876
  • 2
  • 22
  • 33