JPanels and MouseListeners

Hi All,

I can't seem to make an external class listen to a JPanel. Perhaps my code is messed up, i've been trying to solve the problem for a week with no avail.

Thanks in advance,

Hugh

My code is as follows:

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class PanelTest extends JPanel {

public static PanelTest panel;

public static JFrame frame = new JFrame();

public PanelTest(){

frame.setSize(500,500);

frame.setVisible(true);

Listener listener = new Listener();

this.addMouseListener(listener);

}

public void paint(Graphics g) {

g.setColor(Color.red);

g.drawRect(100,100,300,300);

}

public static void main(String[] args) {

panel = new PanelTest();

}

}

class Listener implements MouseListener {

public Listener() {

System.out.println("Listener run");

}

public void mouseClicked(MouseEvent e) {

System.out.println("mouse clicked");

}

public void mousePressed(MouseEvent e) {}

public void mouseReleased(MouseEvent e) {}

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

}

[1273 byte] By [hughsimons] at [2007-9-30 8:11:24]
# 1

You need to add your panel to your frame e.g.,

...

public static void main(String[] args){

JFrame f=new JFrame();

f.setSize(500, 500);

// Add panel to frame here....

f.getContentPane().add(new PanelTest());

f.setVisible(true);

}

...

The panel must be added to the rendering hierarchy in order for it to be "active".

RadcliffePike at 2007-7-2 18:14:52 > top of Java-index,Administration Tools,Sun Connection...