Home arrow static arrow Java Programming [Archive] - Mouse Listener
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Mouse Listener
This topic has 3 replies on 1 page.

Posts:5
Registered: 11/9/03
Mouse Listener  
Aug 1, 2004 7:02 PM



 
I guess I'm one of those rookies..
I'm trying to set up a mouse listener to my Panel. I'm using lots of labels on that panel, but when I click on one of those labels, the program doesn't seem to react. I don't really like to use separate listeners to every label, coz their are too many and their number changes during the running of the program (...). It would be convenient to me if I have that single listener, can somebody give me a hint how to make those labels listen to me?..
Szityu
 

Posts:5
Registered: 11/9/03
Re: Mouse Listener  
Aug 1, 2004 7:19 PM (reply 1 of 3)



 
One detail that might help:
I create the most of the labels at run-time, the program doesn't react on these, though I added them to the contentpane, just like the rest of the labels created design time. The rest of the labels react without any problem.
 

Posts:8,813
Registered: 10/4/00
Re: Mouse Listener  
Aug 1, 2004 8:00 PM (reply 2 of 3)



 
import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.util.Random;public class Test3 extends JFrame {  JPanel labelPanel = new JPanel();  JLabel[] tmpLabels = new JLabel[0];  MouseListener ml = new MouseAdapter() {    public void mouseReleased(MouseEvent me) {      JLabel label = (JLabel)me.getSource();      System.out.println("You pressed "+label.getText());    }  };  Random r = new Random();  int cnt=0;  public Test3() {    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    Container content = getContentPane();    content.add(labelPanel, BorderLayout.CENTER);    for (int i=0; i<5; i++) {      JLabel jl = new JLabel("Perm-"+i);      labelPanel.add(jl);      jl.addMouseListener(ml);    }    JButton jb = new JButton("New Labels");    content.add(jb, BorderLayout.SOUTH);    jb.addActionListener(new ActionListener() {      public void actionPerformed(ActionEvent ae) {        for (int i=0; i<tmpLabels.length; i++) {          tmpLabels[i].removeMouseListener(ml);          labelPanel.remove(tmpLabels[i]);        }        tmpLabels = new JLabel[r.nextInt(25)+5];        cnt++;        for (int i=0; i<tmpLabels.length; i++) {          tmpLabels[i] = new JLabel("Temp-"+cnt+"-"+i);          tmpLabels[i].addMouseListener(ml);          labelPanel.add(tmpLabels[i]);        }        labelPanel.revalidate();      }    });    setSize(300,300);  }  public static void main(String[] args) { new Test3().setVisible(true); }}
 

Posts:5
Registered: 11/9/03
Re: Mouse Listener  
Aug 1, 2004 8:22 PM (reply 3 of 3)



 
Britta, thanks a lot for your help, it solve my problem:)
 
This topic has 3 replies on 1 page.