简体   繁体   中英

which JLabel has been clicked?

I have 6 JLabel and each is having a different instance of a mouselistener class attached. How to know which JLabel has been clicked ? These JLabel form a two dimentional array.

You use getSource to get a refrence to the object which is clicked on:

label1.addActionListener(new yourListener());
label2.addActionListener(new yourListener());

public class yourListener extends MouseAdapter{ 
    public void mouseClicked(MouseEvent e){
        JLabel labelReference=(JLabel)e.getSource();
            labelReference.someMethod();
   }
}

The easiest way I did something like that was, to use JButtons and make them look like JLabels by the using this syntax formatting.

jButton.setBorder( BorderFactory.createEmptyBorder( 2, 2, 2, 2 ) );
jButton.setBorderPainted( false );
jButton.setContentAreaFilled( false );
jButton.setFocusPainted( false );
jButton.setHorizontalAlignment( SwingConstants.LEFT );

Then, what you want to is add an ActionLister and a ActionCommand. For example

jButton.addActionListener( this );
jButton.setActionCommand( "label1" );

Then just handle the actionListners to do what you wanted for each label.

public void actionPerformed( ActionEvent arg0 )
{
    String command = arg0.getActionCommand();
    if( command.equalsIgnoreCase( "label1" ) )
    {
        //label1 code
    }
}

As mentioned below this also has the added benefit of supporting both keyboard and mouse activities.

I put this together based on your description:

public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setLayout(new FlowLayout());
    for (int i = 0; i < 6; i++) {
        JLabel l = new JLabel("Label " + (i + 1));
        l.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                JLabel l = (JLabel) e.getSource(); // here
                System.out.println(l.getText());
            }

        });
        f.add(l);
    }
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
}

I think the line marked // here is mostly what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM