which JLabel has been clicked?

和自甴很熟 提交于 2019-12-04 21:23:34
John Snow

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!