问题描述
我有6个JLabel,每个都附加了一个不同的mouselistener类实例。如何知道点击了哪个JLabel?这些JLabel构成了一个二维数组。
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.
推荐答案
我做这样的最简单的方法是,使用JButton并让它们看起来像JLabels一样使用这种语法格式。
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 );
然后,你想要的是添加一个ActionLister和一个ActionCommand。例如
Then, what you want to is add an ActionLister and a ActionCommand. For example
jButton.addActionListener( this );
jButton.setActionCommand( "label1" );
然后只需处理actionListners即可为每个标签执行所需操作。
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.
这篇关于哪个JLabel被点击了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!