Need Help: adding MouseListeners to JComponents (Drawing a JComponent and then attaching a MouseListener)

Posted by user1074574 on Stack Overflow See other posts from Stack Overflow or by user1074574
Published on 2011-12-01T01:48:35Z Indexed on 2011/12/01 1:50 UTC
Read the original article Hit count: 179

Filed under:
|
|
|
|

Drawing a JComponent and then attaching a MouseListener seems very simple to me, but not in this case: I'm having a problem with a MouseListener attached to a child JComponent; here's some brief code to help describe it:

Note: The BGT class has implemented ActionListers/MouseListeners that do not have any code in them, and 'figures' is an array of SwingThings.

public class GC extends BGT{
 public GC(){
    super();
    buildJMenu();
    drawPanel.addMouseListener(this); //drawPanel being the panel that draws the JComponents (it is a public variable in the BGT class)
    drawPanel.addMouseMotionListener(this);
    this.addMouseListener(this);
}
public static void main(String[] args){
    GC a = new GC();
}...

public void mouseClicked(MouseEvent e) {
    System.out.println(e.getSource()); //This only seems to print out the DrawPanel's information
}...

public void mouseReleased(MouseEvent e) {
    repaint();
    ...
        tempMyJTextField = new MyJTextField(startX, startY, width, height);
        tempMyJTextField.addMouseListener(this);
        tempMyJTextField.addMouseMotionListener(this);
        figures.add(tempMyJTextField);

    for(int i = 0; i < figures.size(); i++)
        figures.get(i).addTo(drawPanel);
}

This is the addTo method in the MyJTextField class:

    public class MyJTextField extends JTextField implements SwingThing{
    ...
    public void addTo(JPanel p) {
    p.add(myTextField);
}
    ...
    }

In the MouseClicked event it never registers that the JComponent was clicked. (The drawing/painting works fine)

Thanks.

© Stack Overflow or respective owner

Related posts about java

Related posts about jpanel