Java,为 JButton 设置 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10070169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:28:13  来源:igfitidea点击:

Java, set ID for JButton

javaswingjbutton

提问by user1321361

Is there anyway to set an id for a JButton. I'm used to it in Android.

无论如何要为JButton. 我在 Android 中已经习惯了。

I'm looking for something like the following:

我正在寻找类似以下内容:

newButton.setId(objectcounter);

回答by Adam

There is a property name which you could use:

您可以使用一个属性名称:

newButton.setName(String.valueOf(objectCounter))

alternatively, you could use clientProperties which lets you store arbitrary values:

或者,您可以使用 clientProperties 来存储任意值:

newButton.putClientProperty("id", Integer.valueOf(objectCounter))

To fetch the value from the client property map you'll need something like this.

要从客户端属性映射中获取值,您需要这样的东西。

Object property = newButton.getClientProperty("id");
if (property instanceof Integer) {
   int objectCounter = ((Integer)property);
   // do stuff
}