查找Java JButton数组的索引 [英] Find the index of a Java JButton Array
问题描述
我正在编写一个Java程序,其中有一个按钮数组(而不是计算器!),并且我正在寻找一种有效的方法来了解单击了哪个JButton.到目前为止,据我所知,Java的唯一方法是将它们全部放在同一个ActionListener中,然后循环查找匹配项.
I am writing a Java program in which I have an array of buttons (not a calculator!) and I'm looking for an efficient way to know which JButton was clicked. From what I know of Java so far, the only way to do it is to have them all in the same ActionListener and then loop through looking for a match.
我刚刚想到的另一种解决方案是扩展JButton以在构造函数中包含唯一的ID号变量.在instanceof检查之后将事件对象强制转换为JButton时,似乎应该可以使用.有点像使用分配给索引号的VB的Tag属性.
Another solution I just thought of would be to extend JButton to include a unique ID number variable in the constructor. It seems that should work when the event object is cast to JButton after an instanceof check. Kind of like using VB's Tag property which is assigned to the index number.
有没有更好/更优雅的方式?
Is there a better/more elegant way?
推荐答案
有没有更好/更优雅的方式?
Is there a better/more elegant way?
-
可以(几乎
JComponent
个)使用 put/getClientProperty ,在那里您可以设置无数个属性,可以与setName
/setActionCommand
/etcyes to use (for almost
JComponent
s) the put/getClientProperty, there you can to set endless number of properties, can be multiplied in contrast withsetName
/setActionCommand
/ etcgetClientProperty
可用作 Swing Action 或 EventHandler (而不是使用getClientProperty
can be used as unique identificator for Swing Action or EventHandler (rather than to use ActionListener)链接到Javadocs: getClientProperty()
Links to the Javadocs: putClientProperty(), getClientProperty()
这篇关于查找Java JButton数组的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!